How do I set up Visual Studio Code to compile C++ code?
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"
}
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.