How do I set up Visual Studio Code to compile C++ code?
Solution 1
The build tasks are project specific. To create a new project, open a directory in Visual Studio Code.
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",
// Pass 'all' as the build target
"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 menu 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.
Solution 2
There is a much easier way to compile and run C++ code, no configuration needed:
- Install the Code Runner Extension
- Open your C++ code file in Text Editor, then use shortcut
Ctrl+Alt+N
, or pressF1
and then select/typeRun Code
, or right click the Text Editor and then clickRun Code
in context menu, the code will be compiled and run, and the output will be shown in the Output Window.
Moreover you could update the config in settings.json using different C++ compilers as you want, the default config for C++ is as below:
"code-runner.executorMap": {
"cpp": "g++ $fullFileName && ./a.out"
}
Solution 3
A makefile task example for new 2.0.0 tasks.json version.
In the snippet below some comments I hope they will be useful.
{
"version": "2.0.0",
"tasks": [
{
"label": "<TASK_NAME>",
"type": "shell",
"command": "make",
// use options.cwd property if the Makefile is not in the project root ${workspaceRoot} dir
"options": {
"cwd": "${workspaceRoot}/<DIR_WITH_MAKEFILE>"
},
// 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
}
}
}
]
}
Solution 4
Here is how I configured my VS for C++
Make sure to change appropriete paths to where your MinGW installed
launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "C++ Launch (GDB)",
"type": "cppdbg",
"request": "launch",
"targetArchitecture": "x86",
"program": "${workspaceRoot}\\${fileBasename}.exe",
"miDebuggerPath":"C:\\mingw-w64\\bin\\gdb.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceRoot}",
"externalConsole": true,
"preLaunchTask": "g++"
}
]
}
tasks.json
{
"version": "0.1.0",
"command": "g++",
"args": ["-g","-std=c++11","${file}","-o","${workspaceRoot}\\${fileBasename}.exe"],
"problemMatcher": {
"owner": "cpp",
"fileLocation": ["relative", "${workspaceRoot}"],
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
}
}
c_cpp_properties.json
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceRoot}",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/x86_64-w64-mingw32",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/backward",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/tr1",
"C:/mingw-w64/x86_64-w64-mingw32/include"
],
"defines": [
"_DEBUG",
"UNICODE",
"__GNUC__=6",
"__cdecl=__attribute__((__cdecl__))"
],
"intelliSenseMode": "msvc-x64",
"browse": {
"path": [
"${workspaceRoot}",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/x86_64-w64-mingw32",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/backward",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include",
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/tr1",
"C:/mingw-w64/x86_64-w64-mingw32/include"
]
},
"limitSymbolsToIncludedHeaders": true,
"databaseFilename": ""
}
],
"version": 3
}
Reference:
Solution 5
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
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}\\build\\${fileBasenameNoExtension}", //output file name
"&&", //to join building and running of the file
"${workspaceFolder}\\build\\${fileBasenameNoExtension}"
],
"group": {
"kind": "build", //defines to which group the task belongs
"isDefault": true
},
"presentation": { //Explained in detail below
"echo": false,
"reveal": "always",
"focus": true,
"panel": "shared",
"clear": false,
"showReuseMessage": false
},
"problemMatcher": "$gcc"
},
]
}
Now , stating directly from the VS code tasks documentation
description of type property :
- type: The task's type. For a custom task, this can either be shell or process. If shell is specified, the command is interpreted as a shell command (for example: bash, cmd, or PowerShell). If process is specified, the command is interpreted as a process to execute.
The behavior of the terminal can be controlled using the presentation property in tasks.json . It offers the following properties:
reveal: Controls whether the Integrated Terminal panel is brought to front. Valid values are: - always - The panel is always brought to front. This is the default - never - The user must explicitly bring the terminal panel to the front using the View > Terminal command (Ctrl+`). - silent - The terminal panel is brought to front only if the output is not scanned for errors and warnings.
focus: Controls whether the terminal is taking input focus or not. Default is false.
echo: Controls whether the executed command is echoed in the terminal. Default is true.
showReuseMessage: Controls whether to show the "Terminal will be reused by tasks, press any key to close it" message.
panel: Controls whether the terminal instance is shared between task runs. Possible values are: - shared: The terminal is shared and the output of other task runs are added to the same terminal. - dedicated: The terminal is dedicated to a specific task. If that task is executed again, the terminal is reused. However, the output of a different task is presented in a different terminal. - new: Every execution of that task is using a new clean terminal.
clear: Controls whether the terminal is cleared before this task is run. Default is false.
Related videos on Youtube
Peter Mortensen
Experienced application developer. Software Engineer. M.Sc.E.E. C++ (10 years), software engineering, .NET/C#/VB.NET (12 years), usability testing, Perl, scientific computing, Python, Windows/Macintosh/Linux, Z80 assembly, CAN bus/CANopen. Contact I can be contacted through this reCAPTCHA (requires JavaScript to be allowed from google.com and possibly other(s)). Make sure to make the subject specific (I said: specific. Repeat: specific subject required). I can not stress this enough - 90% of you can not compose a specific subject, but instead use some generic subject. Use a specific subject, damn it! You still don't get it. It can't be that difficult to provide a specific subject to an email instead of a generic one. For example, including meta content like "quick question" is unhelpful. Concentrate on the actual subject. Did I say specific? I think I did. Let me repeat it just in case: use a specific subject in your email (otherwise it will no be opened at all). Selected questions, etc.: End-of-line identifier in VB.NET? How can I determine if a .NET assembly was built for x86 or x64? C++ reference - sample memmove The difference between + and & for joining strings in VB.NET Some of my other accounts: Careers. [/]. Super User (SU). [/]. Other My 15 minutes of fame on Super User My 15 minutes of fame in Denmark Blog. Sample: Jump the shark. LinkedIn @PeterMortensen (Twitter) Quora GitHub Full jump page (Last updated 2021-11-25)
Updated on May 06, 2021Comments
-
Peter Mortensen almost 3 years
Microsoft's Visual Studio Code editor is quite nice, but it has no default support for building C++ projects.
How do I configure it to do this?
-
Charles Milette over 7 yearsThere's a lot of answers for compiling C++ code under Linux, but what about Windows?
-
Kshitij about 7 yearsSuch a basic things and yet there is no helpful resource to do this in windows. And ms cpptools extension, don't talk about that. I guess it is just to add to your frustration. It does nothing.
-
Mahesha999 about 7 years
-
-
Mahesha999 about 7 years
-
Hichigaya Hachiman over 6 yearsMy Output window is stucked at
running blablabla
. No prompt, nothing. How do I even stop the code running? -
Jun Han over 6 yearsTo stop code running, use
Ctrl+Alt+M
. To use stdin to read data, you could go toFile
->Preference
->Settings
to set"code-runner.runInTerminal": true
. For more details, you could refer to github.com/formulahendry/vscode-code-runner/issues/91 -
Louis over 6 yearsI'm using the latest VSC. You lost me at Step 4. Configure task runner is not available.
-
uitty400 almost 6 yearsmaybe you also want to explain a bit what your settings are doing and not just copy paste stuff
-
Li Kui almost 6 yearsit's hard for me to explain my settings.
-
jhpratt over 5 yearsThis is a borderline link-only answer. You should expand your answer to include as much information here, and use the link only for reference.
-
TheIntern over 5 yearsStill up to date in November 2018. Thanks!
-
Andrew Wolfe about 5 yearsRunning in the output window prevents terminal input. runInTerminal seems necessary...
-
breakpoint about 5 yearsWARNING - the format of this file has changed, and this is no longer correct. See: go.microsoft.com/fwlink/?LinkId=733558
-
breakpoint about 5 yearsIn what directory did you place this? The root, ".vs", or ".vscode"? Supposedly, the workspace root is the only recommended location if the file is also going into revision control (which I strongly recommend), but I couldn't get that to work.
-
breakpoint about 5 yearsHere's the build-scripts/build-debug.sh file, as an example. Ideally these would inherit the build context (debug, release, profiling, etc.) but I can't figure out how Code manages that, if it even has the concept. Pardon the formatting; go, StackOverflow, go. #!/bin/bash if [ ! -d "DEBUG" ]; then mkdir DEBUG meson DEBUG fi cd DEBUG ninja if [ $? -eq 0 ]; then exit 0 else exit $? fi
-
breakpoint about 5 yearsOh, again: press CTRL-SHIFT-B after this is in place to pull up the build tasks. I'd really, really prefer a proper main-menu full of these, but I haven't figured out how to do that yet.
-
attdona about 5 yearsFor what I know, the only valid place at the moment is
.vscode
. For git revision control one possibility is to use for.gitignore
a pattern like!.vscode/tasks.json
. -
Melroy van den Berg about 5 yearsDefault key is
ctrl+alt+b
for the build task. -
Gaurav almost 5 yearsGetting an error - "error: empty filename in #include"
-
Dan L almost 5 yearsIs there a command or binding that will jump to next/previous error in the terminal? I have a situation where the "Problems" pane has a bunch of irrelevant issues (because VS Code doesn't really know how to build my project -- and it'll be way too involved to teach it) but my "Terminal" is full of useful errors after a build. I just need a keyboard shortcut to jump to the next error in the "Terminal"...
-
Anthony Lei almost 5 yearsMake sure to change appropriete paths to where your MinGW installed.
-
Peter Chaula over 4 yearsThat extension has a ~5 star rating which leads me to believe that it works
-
Seaky Lone over 4 yearsI just want to print hello world but why do I get this: 'g++' �����ڲ����ⲿ���Ҳ���ǿ����еij��� ���������ļ���?
-
exilour over 4 yearsThis now works out of the box for C/C++. @SeakyLone you will have to install and add a C++ (try Mingw) compiler to the system environment path. (I am guessing you are on Windows). If you are on Linux install G++.
-
JDługosz over 4 yearsThis is a repeat of earlier answers.
-
Codebling over 4 yearsYou should disclose that you are the author of the extension you are promoting.
-
M.M about 4 yearsCtrl+ zooms in for me
-
Ashley Fernandes about 4 yearsit's ctrl comma not ctrl plus to open settings
-
questionto42standswithUkraine almost 4 yearsYou can also include subfolders recursively with /** instead of repeating various subfolders in
"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include"
-
0dminnimda over 2 years
-
nights over 2 yearsyou still need to install g++ though?