How to configure VS Code to compile/debug C++? - 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.

Related

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.

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

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).

Building a C++ Program in Visual Studio Code

To my knowledge, I have followed all of the steps to build a C++ program in Visual Studio Code on Windows 10. I have gcc-7.1.0-64 installed under C:/MinGW, the C/C++ extension installed in VS Code, and have configured a build task for my HelloWorld.cpp.
The issue:
When I try to build the program by opening the Command Palette and then typing Tasks: Run Build Task, It displays the error:
No Build Task found. Press 'Configure Build Task' to define one.
despite the fact that I have already done exactly that. I am probably missing something simple, but no tutorial or documentation I could find anywhere explains how to make this work. Any help is appreciated.
HelloWorld.cpp
#include <iostream>
using namespace std;
int main() {
std::cout << "Hello world\n";
}
c_cpp_properties.json (irrelevant Mac/Linux setup omitted from snippet)
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceRoot}",
"C:/MinGW/include/c++/7.1.0/*"
],
"defines": [
"_DEBUG",
"UNICODE"
],
"intelliSenseMode": "msvc-x64",
"browse": {
"path": [
"${workspaceRoot}",
"C:/MinGW/include/c++/7.1.0/*"
],
"limitSymbolsToIncludedHeaders": true,
"databaseFilename": ""
}
}
],
"version": 2
}
tasks.json
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"taskName": "HelloWorld.cpp",
"command": "c++",
"args": ["-g", "HelloWorld.cpp"],
"type": "shell"
}
]
}
Thanks to #RobLourens's comment for the answer.
The easiest way for tasks 2.0 is, run "Configure default build task", which will let you pick the build command, and set the group property for you.
I soon realized that it adds a line under the "group" section of the specified build task in tasks.json: (may be added manually to circumvent the formal method)
"isDefault": true,
Just add "isBuildCommand": true inside your task.

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 prepare/configure development environment for C++ projects in Visual Code Editor?

I'm working with JavaScript projects using nodejs and visual code editor. I wonder is it possible to configure such a great code editor for C++ projects.
I want to link the debugger and make some hotkeys for building the debug/release versions of project.
Is it possible for C++ projects and what should I do/read for it?
I want to link the debugger
This is currently not possible until there is a public extension API available. I expect it to come in November or December this year.
I want to [...] make some hotkeys for building the debug/release versions of project.
You can do it right now if there is only one project you want to compile in your workspace.
This is how to do it:
Open the root folder of your project in VSCode (this is your workspace)
Place a batch/shell script in the workspace that accepts a parameter with a value of release/debug and compiles the project in release or debug mode depending on the passed parameter value
In case there is no .vscode directory in the workspace then create it on your own
Add a file tasks.json to that folder having this content:
{
"version": "0.1.0",
"command": "${workspaceRoot}/CompileProject.bat",
"tasks": [
{
"taskName": "Compile debug build",
"args": [
"debug"
],
"isTestCommand": true
},
{
"taskName": "Compile release build",
"args": [
"release"
],
"isBuildCommand": true
}
]
}
You can trigger Compile debug build with CTRL + Shift + T and Compile release build with CTRL + Shift + B.
You can change the keybindings by going to File -> Preferences -> Keyboard Shortcuts and define your preferred shortcuts for the commands workbench.action.tasks.test and workbench.action.tasks.build.
Example:
[
{ "key": "f5", "command": "workbench.action.tasks.test" },
{ "key": "f6", "command": "workbench.action.tasks.build" }
]
Use the following in the tasks.json file, changing "helloworld" strings as appropriate.
// Available variables which can be used inside of strings.
// ${workspaceRoot}: the root folder of the team
// ${file}: the current opened file
// ${fileBasename}: the current opened file's basename
// ${fileDirname}: the current opened file's dirname
// ${fileExtname}: the current opened file's extension
// ${cwd}: the current working directory of the spawned process
{
"version": "0.1.0",
"command": "gcc",
"args": ["-Wall", "helloWorld.c", "-o", "helloWorld"],
"problemMatcher": {
"owner": "cpp",
"fileLocation": ["relative", "${workspaceRoot}"],
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
}
}
EDIT: This requires gcc to be available on the path. The build can be triggered with Ctrl + shift + b.
Debugger is not available yet AFAIK