VS Code "command": "make" differs from command line `make` in terminal window - c++

I installed VS Code for Linux some time ago, opened a C ++ project in the workspace, created tasks.json - in general I did everything according to Google.
When I run the make command in a terminal window, everything is OK. But when I do the same (Ctrl+Shift+B) from VS Code I get an error.
Processing my Makefile terminates after the command libtool: link: c++ -fPIC -DPIC -shared -nostdlib /usr/bin/../lib/gcc/x86_64-linux-gnu/7.3.0/../../../x86_64-linux-gnu/crti.o ....
with message
c++: error: /usr/bin/../lib/gcc/x86_64-linux-gnu/7.3.0/../../../x86_64-linux-gnu/crti.o: No such file or directory.
Of course, the path is correct (and is good when I use the command line make in a terminal window).
Contents of tasks.json is trivial (same as in microsoft.com):
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "ClanLib",
"type": "shell",
"command": "make",
// start the build without prompting for task selection, use "group": "build" otherwise
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "shared"
},
// arg passing example: in this case is executed make QUIET=0
"args": ["QUIET=0"],
// Use the standard less compilation problem matcher.
"problemMatcher": {
"owner": "cpp",
"fileLocation": ["absolute"],
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
}
}
]
}
I can't post Makefile, it consists of thousands of lines of code after autogeneration from https://github.com/sphair/ClanLib...
Please help with setting up Visual Studio Code (Linux Mint).

It looks like you try build manually with your makefile within a directory, and vscode from another.
If it is the case, you can tell your tasks to run from a specific directory with the cwd option - doc:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "ClanLib",
"type": "shell",
"command": "make",
"options": {
"cwd": "${workspaceRoot}/<DIR_WITH_MAKEFILE>"
}
...
}]}

It seems I felt something. In the terminal window inside VSCode I see
sh-4.4$ help
GNU bash, версия 4.4.19(1)-release (x86_64-unknown-linux-gnu)
But in the OS terminal:
art#artPC:~/git/ClanLib$ help
GNU bash, версия 4.4.19(1)-release (x86_64-pc-linux-gnu)
The difference is -unknown- and -pc-. Result of whoami is the same on both terminals.
And finally in VSCode terminal:
sh-4.4$ ls
x86_64-unknown-linux-gnu
Name of symbolic-link x86_64-unknown-linux-gnu is defferent between OS and VSCode. Bug of VSCode?

The solution is here
https://github.com/Microsoft/vscode/issues/62532
Thanks for mr. #jerch
you have different build sets installed, see "GNU Make 4.1" vs. "GNU Make 4.2.1". For some reason /bin/sh defaults to the other one. To fix that you have to consult your distro's help (in Ubuntu you can switch buildsets with the update-alternatives command).

Related

Spotlight Search, Mail Search, C++ compiling not working on macOS after PATH Modification or Ventura Update

I recently made a couple of changes on my Mac.
Intending to start working with C++ I installed cmake and modified my $PATH variable.
I updated to the newest version of Ventura.
Now, spotlight search and apple mail are not working working anymore. Additionally (and more annoying), I cannot debug, and compile cpp files as before in VS-Code.
But receive the following error message:
Starting build...
/opt/homebrew/bin/g++-11 -fdiagnostics-color=always -g "/Users/jakobnitschke/Library/Mobile Documents/com\~apple\~CloudDocs/PhD/Learning_cplusplus/Jumping_into_cpp/sample_code/ch1/hello.cpp" -o "/Users/jakobnitschke/Library/Mobile Documents/com\~apple\~CloudDocs/PhD/Learning_cplusplus/Jumping_into_cpp/sample_code/ch1/hello"
/bin/sh: /opt/homebrew/bin/g++-11: No such file or directory
Build finished with error(s).
* The terminal process failed to launch (exit code: -1).
* Terminal will be reused by tasks, press any key to close it.
My current $PATH:
/Users/jakobnitschke/opt/anaconda3/bin
/Users/jakobnitschke/opt/anaconda3/condabin
/opt/homebrew/bin
/Library/Frameworks/Python.framework/Versions/3.10/bin
/opt/local/bin
/opt/local/sbin
/usr/local/bin
/System/Cryptexes/App/usr/bin
/usr/bin
/bin
/usr/sbin
/sbin
/Library/TeX/texbin
/opt/X11/bin
/Library/Apple/usr/bin
Because I noticed a problem first through the errors in Spotlight and Apple Mail, I tried to reindex the spotlight search and followed several procedures on the apple forum but none solved my issue.
One of the first things was to properly update the Command Line Developer tools but this did not solve the issues.
Since, I looked into ways of resetting my $PATH and found ways to do it but I don't know which should be my final $PATH to set since I am scarred to mess up other parts of my programming environment with Python and R.
You should (within your project folder) look for a file named tasks.json this file configures the tasks for your Visual Studio Code. This is an example file I took from a different question I answered some time ago:
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++ build active file",
"command": "/usr/bin/g++",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}",
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "Task generated by Debugger."
}
],
"version": "2.0.0"
}
If you look closely there is a line with an element named "command":
You will most-likely have something like "command": "/opt/homebrew/bin/g++-11" there.
Change it to "command": "/opt/homebrew/bin/g++-12"
EDIT: You can also create a symbolic-link for g++ in your /usr/bin folder that points to your homebrew installation of g++. This should save you a lot of issues when working with VSCode.

Configure vscode to build and run c++ in one terminal

I installed mingw64 toolchain with MSYS2, and managed to successfully run my code from vscode. However, running it creates two terminals, one for building and one for running the generated file: C/C++: g++.exe build active file and cppdbg: main.exe.
cppdbg: main.exe leaves the text from the previous runs and "presentation" { "clear": true } in launch.json doesn`t help.
since build and run are not related, it's possible that the build will fail and the old .exe will be launched without me noticing it.
So I'm looking for a way to configure vscode to build and run the app in one terminal, or maybe redirect the compiler output to the output tab. Anything similar to how it's done in other languages.
Also, how can I configure it to run without debugging by default? In launch.json, "configurations" require a "type" parameter, which has only one option, "cppdbg" - why is there no release option?
You are asking two questions and I can answer both.
How do I build and debug the application, by making sure that it is launched only when the build is successful?
How do I configure it to run the application similarly?
Let me answer 2 first.
To solve this, you need the dependsOn property of tasks. For example, this is the content of my tasks.json file:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks":
[
{
"label": "Debug_Build",
"type": "shell",
"command": "g++ -g ./src/main.cpp -o ./bin/a.out",
},
{
"label": "Run main()",
"type": "shell",
"command": "./bin/a.out",
"dependsOn":"Debug_Build" //Previous task is run first, and then this one if previous was successful.
}
]
}
Notice that the second task (which is responsible for running the program) has dependsOn property which behaves exactly as you require: It will run only when the dependsOn task is successful (Which here is the build task)
To run the tasks, you can use the Command Palette to Run
Tasks>Run main()
to launch your task. Personally, I prefer using the extension Tasks, which creates a button for each task in the tasks.json file on the status bar of VS Code.
Now to answer 1, we use a similar property in the launch configuration json file: preLaunchTask
This will be exactly what you need: It will run the debugging only if the preLaunchTask was successful.
My launch.json file is as follows:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/bin/a.out",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "Debug_Build", //This is the part you need
}
]
}
So to summarize, you will need to create tasks.json and launch.json files in your workspace. In the tasks.json file, declare a "build" task, declare the "run" task which depends on the "build" task using the dependsOn property. Finally, in the launch.json file, refer the "build" task in the preLaunch property.

How to compile and run a c++ source file in visual studio code

I've searched for an answer to this question, but couldn't seem to find one. I know that we can use task.json files to automate the build process. But I want to use Visual Studio Code to implement algorithms in C++ for competitive programming. I want to be able to compile a program, and run it all in one go, if there aren't any errors. If there are errors, I would like them to be displayed.
Also, visual studio code comes with an integrated terminal, so it would be nice if the program output could be redirected there.
Also, how can we map a keyboard shortcut to run this task.
I'm using Visual Studio Code 2019 on Windows 10 with the MinGW G++ compiler.
EDIT
I've tried Escape0707's answer below, and I tried executing 'Run Code' with the default key binding of Ctrl + Alt + N but I'm getting this error.
Updated method which combines make and vscode-cpptools debug:
If you don't care about VSCode integrated debugging tools, which will give you the ability to set breakpoints, change variable value during runtime, inspect variable value, and etc, and you want a somewhat easier, simpler, faster, transparent way to invoke the good old command line tools, skip this section and checkout Code Runner below.
The default configurations come with VSCode C++ extension are kind of slow for low-end machines. The worst part is that they will always rebuild your executable, and don't support 'Start Without Debugging'. Below is a workaround for Linux (and of course remote-WSL).
To address the first issue, you setup make (for simple one source file compiling you only need to install make) to build your source codes, and setup the build task in tasks.json. To address the second issue, you create another task just to run the built executable after the first task finished:
Use Intellisense to learn about each properties in configs.
tasks.json
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"presentation": {
"clear": true,
"focus": true,
"panel": "shared"
},
"tasks": [
{
"label": "make active file",
"type": "shell",
"command": "make",
"args": ["${fileBasenameNoExtension}.out"],
"problemMatcher": "$gcc",
"group": {
"kind": "build",
"isDefault": true
}
},
{
"label": "run active file executable without debuging",
"type": "shell",
"command": "${fileDirname}/${fileBasenameNoExtension}.out",
"presentation": {
"clear": false
}
},
{
"label": "make and run active file without debuging",
"group": {
"kind": "test",
"isDefault": true
},
"dependsOn": [
"make active file",
"run active file executable without debuging"
],
"dependsOrder": "sequence"
}
]
}
To enable debugging using VSCode in this way, first make sure you added -g compile flag to CXXFLAGS in Makefile.
For quick information about how to write a Makefile, see this, or this, or this. Or check this last part of this answer.
Then, create the following launch.json:
launch.json
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "make and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}.out",
"cwd": "${workspaceFolder}",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "${defaultBuildTask}"
}
]
}
Now you can use command palette to try Task: Run Build Task, Task: Run Test Task, Debug: Start Debugging.
Original answer
Please consider Code Runner, as it seems faster (for me) than VSCode's built-in debug procedure for practicing with many small C++ code files. I'll describe how I use that extension to satisfy a similar requirement.
Make sure you've configured your PATH to include clang++ so you can invoke it from the integrated terminal.
You can also use g++ by substitute clang++ below with g++. I prefer clang++ as it provides stricter checks for C++ beginners like me.
Install the extension.
In your VSCode's settings.json, consider adding the following entries:
"code-runner.clearPreviousOutput": true,
"code-runner.preserveFocus": false,
"code-runner.runInTerminal": true,
"code-runner.saveFileBeforeRun": true
And add the last customization code-runner.executorMap to user/workspace setting that describes which command you would like the extension to send to the terminal when current filename's extension meets the specified ones. For example:
"code-runner.executorMap": {
"cpp": "\b\b\b\b\b\b\b\b\b\bclang++ -std=c++17 $fileName -o a.out && ./a.out"
},
The above setting tells the extension, "When see a .cpp file, send 10 Backspace to terminal (to delete any mistyped characters) and call clang++ -std=c++17 *filename* -o a.out && ./a.out.
I use this command on my Linux machine, for Windows, try change the filename extension of the output file to .exe and invoke it with .\a.exe or simply a.exe.
Finally, map the Run Code command to your preferred keybinding in VSCode's Keyboard Shortcuts settings. Mine is to bind it to F5 which is originally bound to Debug: Continue.
Happy coding!
Update about make
Read on to learn how to avoid redundant compiling process and speed up case test by utilizing GNU make. I'll do this on Linux and only for C++, since I have not used make on Windows or OS X and C++ is the best for ACM.
Make sure make is installed and in your PATH
Create a file named Makefile (or makefile) under the same directory you invoke make. (Or in another directory and make -f /path/to/Makefile).
Redefine compiler options to whatever you like in the Makefile, e.g.:
CXX = clang++
CXXFLAGS = -std=c++17 -g -Weverything -Werror
Create auto-target rule for *.out in the Makefile, i.e.:
%.out: %.cpp
$(LINK.cpp) $^ $(LOADLIBES) $(LDLIBS) -o $#
Attention: must use Tab to indent the second line, not Spaces.
Change code-runner.executorMap to :
"code-runner.executorMap": {
"cpp": "\b\b\b\b\b\b\b\b\b\bmake $fileNameWithoutExt.out && ./$fileNameWithoutExt.out"
(Optional) To ignore *.out for git:
echo "*.out" >> .gitignore
(Optional) To remove *.out in current directory:
rm *.out
Now the Run Code command will invoke make and make will only regenerate .out file when the corresponding .cpp file is newer than the .out file, thus allows us to skip compilation and proceed with testing even smoother.
The CXXFLAGS is for C++ compiler options, CFLAGS is for C compiler options. You can find other language compiler options and their variable name using make -p, Google and GNU make manual#Automatic-Variables.
To Build/run C++ projects in VS code , you manually need to configure tasks.json file which is in .vscode folder in workspace folder . To open tasks.json , press ctrl + shift + P , and type Configure tasks , and press enter, it will take you to tasks.json
Here i am providing my tasks.json file with some comments to make the file more understandable , It can be used as a reference for configuring tasks.json , i hope it will be useful
After configuring tasks.json , to compile and run your c++ file , press ctrl+shift+B , this is shortcut for running build tools in vscode . Your C++ program will now run on vscode integrated terminal only .
If this presents some issues , then change default terminal to cmd(by default it is powershell in windows) and make sure there aren't any spaces in path to your file .
tasks.json
{
"version": "2.0.0",
"tasks": [
{
"label": "build & run", //It's name of the task , you can have several tasks
"type": "shell", //type can be either 'shell' or 'process' , more details will be given below
"command": "g++",
"args": [
"-g", //gnu debugging flag , only necessary if you want to perform debugging on file
"${file}", //${file} gives full path of the file
"-o",
"${workspaceFolder}\\${fileBasenameNoExtension}", //output file name
"&&", //to join building and running of the file
"${workspaceFolder}\\${fileBasenameNoExtension}"
],
"group": {
"kind": "build", //defines to which group the task belongs
"isDefault": true
},
"presentation": {
"echo": false,
"reveal": "always",
"focus": true,
"panel": "shared",
"clear": false,
"showReuseMessage": false
},
"problemMatcher": "$gcc"
},
]
}
All the properties in the presentation of tasks.json are just used to customize build tasks as per your needs , feel free to change them to what you like best . You can read about presentation properties (and other things) on vscode tasks documentations

How to build and run C++ code in Visual Studio Code?

I have a tasks.json script that currently compiles the code
{
"version": "0.1.0",
"command": "gcc",
"isShellCommand": true,
"args": ["-Wall", "${relativeFile}", "-o", "${relativeFile}.exe", "-pedantic"],
"echoCommand": true,
"showOutput": "always",
"problemMatcher": {
"owner": "cpp",
"fileLocation": ["relative", "${workspaceRoot}"],
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
}
}
This works fine, but when I want to run the file I have to run the exe from command line. Is it possible to do this in the task as well? So if it finishes building succesfully it then runs a different task?
If anyone else comes across this when searching like I did, you can now set the property preLaunchTask in your launch.json to your build task's name property and it will run before your launch.
For Example
"name": "Debug (gdb) Launch",
"preLaunchTask": "Build All",
Will run the "name": "Builld All" in your tasks.json before launching your program.
You can read the information on this on the Debugging in Visual Code docs page.
You can configure multiple tasks in Visual Studio Code, one of which will allow you to build your executable, and the other will run your executable.
Optionally, you could also look into Visual Studio Code's "Run Mode" (see here). If you use "Run Mode", you should be able to configure Visual Studio Code to build your executable, and then launch it.
I'm not extremely familiar with "Run Mode", thus I will detail how to define multiple tasks to achieve a similar result.
Disclaimer: Visual Studio Code does not support tasks that use different shell commands (see here).
That's right. At its current state, Visual Studio Code doesn't have "native" support for defining tasks that use different shell commands.
Disclaimer: Visual Studio Code's task-output pane will not allow you to pass input to your program interactively.
If your program relies on user-input (for example, from stdin), you're probably better off not using Visual Studio Code to run your executable.
Basically, what we'll need to do, is define two tasks, one of which will be a build task, the other will be our launch task.
Seeing as Visual Studio Code doesn't have great support for defining multiple tasks that each use different shell commands, we'll need to change our tasks.json's "command" property to cmd (or sh, if on Linux/macOS). We'll also need to set the "args" property to [/C] ([-c] if on Linux/macOS).
The reason behind us doing this, is because we want each of the tasks we're about to define, to be passed as arguments to a new shell instance.
The next step, is to define our build and launch tasks. When we do so, we'll need to make sure we place the command we want to run, as a task argument. For example:
{
"taskName": "build",
"args": ["gcc", "-Wall", "${relativeFile}", "-o", "${relativeFile}.exe", "-pedantic"]
}
Finally, what we'll do, is add the "isBuildCommand" property to our build task (and make sure it's true), as well as add the "isTestCommand" property to our launch task (and, again, make sure it's true).
After all of that, our tasks.json file could look something like this:
{
"version": "0.1.0",
"command": "cmd",
"args": ["/C"],
"isShellCommand": true,
"showOutput": "always",
"suppressTaskName": true,
"tasks": [
{
"taskName": "build",
"args": ["gcc", "-Wall", "${relativeFile}", "-o", "${relativeFile}.exe", "-pedantic"],
"isBuildCommand": true
},
{
"taskName": "run",
"args": ["${relativeFile}.exe"],
"isTestCommand": true
}
]
}
Note: If placing each task argument in their own string within the args array doesn't work, you can also try placing all of the arguments in a single string within the args array. Example:
["gcc -Wall ${relativeFile} -o ${relativeFile}.exe -pedantic"]
Note: If you would like to be able to invoke your task(s) via keyboard shortcuts, you have the "workbench.action.tasks.build" and "workbench.action.tasks.test" editor commands at your disposal.
If you need an example of binding keys to those commands, here's an example of how I have them mapped in my keybindings.json file:
[
{
"key": "f6",
"command": "workbench.action.tasks.build"
},
{
"key": "f7",
"command": "workbench.action.tasks.test"
}
}
Edit: You probably only need to define a keyboard shortcut for the test task, as the build task probably already has one defined. Check here before you take the time to define a different keyboard shortcut.
You can create a task for build and as the arguments of it you can pass the commands for running. As an example the task I use to compile and run c++ is shown below.
{
"version": "2.0.0",
"tasks": [
{
"label": "g++ build and run",
"type": "shell",
"command": "g++",
"args": [
"-g",
"-o",
"out.exe",
"\"${file}\"",
"&&",
"./out.exe",
"<",
"input.in",
">",
"output.out"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
In the above task I compile my source file (the name of the file could be anyone here as ${file} is used) into out.exe and the run out.exe while getting input from input.in and outputting the output to output.out.

How to configure VS Code to compile/debug C++?

I've installed the C/C++ extension for VS Code but am not quite sure what I need to have in my tasks.json in order to compile a project. Is there an example I can look at somewhere?
Also, the extension refers to Clang tools, I kind of assumed that Clang doesn't work on Windows.
Here is a webpage where they explain more about the task.json file.
https://code.visualstudio.com/docs/editor/tasks
The build tasks are project specific. To create a new project, open a directory in VSCode.
Following the instructions here, press Ctrl+Shift+P, type Configure Tasks, select it and press Enter.
The tasks.json file will be opened. Paste the following build script into the file, and save it:
{
"version": "0.1.0",
"command": "make",
"isShellCommand": true,
"tasks": [
{
"taskName": "Makefile",
// Make this the default build command.
"isBuildCommand": true,
// Show the output window only if unrecognized errors occur.
"showOutput": "always",
// No args
"args": ["all"],
// Use the standard less compilation problem matcher.
"problemMatcher": {
"owner": "cpp",
"fileLocation": ["relative", "${workspaceRoot}"],
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
}
}
]
}
Now go to File->Preferences->Keyboard Shortcuts and add the following key binding for the build task:
// Place your key bindings in this file to overwrite the defaults
[
{ "key": "f8", "command": "workbench.action.tasks.build" }
]
Now when you press F8 the Makefile will be executed and errors will be underlined in the editor.