How do I set up Visual Studio Code to compile C++ code?
Asked Answered
K

13

276

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?

Kitchenware answered 15/5, 2015 at 22:6 Comment(3)
There's a lot of answers for compiling C++ code under Linux, but what about Windows?Vinosity
Such 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.Rooney
Anyone found solution? I am able to compile, but not debug C/C++ on VSCode. This article says debugging is supported only on linux. Also recently I created this thread for the same. Will appreciate any help...Expertize
K
100

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

Kitchenware answered 15/5, 2015 at 22:6 Comment(3)
WARNING - the format of this file has changed, and this is no longer correct. See: go.microsoft.com/fwlink/?LinkId=733558Almagest
Default key is ctrl+alt+b for the build task.Pelican
Is 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"...Cletis
M
57

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
                }
            }
        }
    ]
}
Mackenziemackerel answered 1/10, 2017 at 8:28 Comment(2)
In 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.Almagest
For 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.Mackenziemackerel
K
20

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:

  1. C/C++ for VS Code

  2. c_cpp_properties.json template

Kleinstein answered 21/3, 2018 at 6:18 Comment(4)
maybe you also want to explain a bit what your settings are doing and not just copy paste stuffContextual
it's hard for me to explain my settings.Kleinstein
Make sure to change appropriete paths to where your MinGW installed.Ethology
You 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"Ninos
V
17

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.

Visional answered 4/6, 2019 at 17:51 Comment(0)
A
11

Out of frustration at the lack of clear documentation, I've created a Mac project on github that should just work (both building and debugging):

vscode-mac-c-example

Note that it requires XCode and the VSCode Microsoft cpptools extension.

I plan to do the same for Windows and linux (unless Microsoft write decent documentation first...).

Actuary answered 9/5, 2017 at 14:49 Comment(0)
A
11

First of all, goto extensions (Ctrl + Shift + X) and install 2 extensions:

  1. Code Runner
  2. C/C++

Then, then reload the VS Code and select a play button on the top of the right corner your program runs in the output terminal. You can see output by Ctrl + Alt + N. To change other features goto user setting. enter image description here

Antho answered 20/11, 2019 at 16:20 Comment(1)
This is a repeat of earlier answers.Champagne
A
7

The basic problem here is that building and linking a C++ program depends heavily on the build system in use. You will need to support the following distinct tasks, using some combination of plugins and custom code:

  1. General C++ language support for the editor. This is usually done using ms-vscode.cpptools, which most people expect to also handle a lot of other stuff, like build support. Let me save you some time: it doesn't. However, you will probably want it anyway.

  2. Build, clean, and rebuild tasks. This is where your choice of build system becomes a huge deal. You will find plugins for things like CMake and Autoconf (god help you), but if you're using something like Meson and Ninja, you are going to have to write some helper scripts, and configure a custom "tasks.json" file to handle these. Microsoft has totally changed everything about that file over the last few versions, right down to what it is supposed to be called and the places (yes, placeS) it can go, to say nothing of completely changing the format. Worse, they've SORT OF kept backward compatibility, to be sure to use the "version" key to specify which variant you want. See details here:

https://code.visualstudio.com/docs/editor/tasks

...but note conflicts with:

https://code.visualstudio.com/docs/languages/cpp

WARNING: IN ALL OF THE ANSWERS BELOW, ANYTHING THAT BEGINS WITH A "VERSION" TAG BELOW 2.0.0 IS OBSOLETE.

Here's the closest thing I've got at the moment. Note that I kick most of the heavy lifting off to scripts, this doesn't really give me any menu entries I can live with, and there isn't any good way to select between debug and release without just making another three explicit entries in here. With all that said, here is what I can tolerate as my .vscode/tasks.json file at the moment:

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build project",
            "type": "shell",
            "command": "buildscripts/build-debug.sh",
            "args": [],

            "group": {
                "kind": "build",
                "isDefault": true
            },
            "presentation": {
                // Reveal the output only if unrecognized errors occur.
                "echo": true,
                "focus": false,
                "reveal": "always",
                "panel": "shared"
            },

            // Use the standard MS compiler pattern to detect errors, warnings and infos
            "options": {
                "cwd": "${workspaceRoot}"
            },
            "problemMatcher": {
                "owner": "cpp",
                "fileLocation": ["relative", "${workspaceRoot}/DEBUG"],
                "pattern": {
                    "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        },
        {
            "label": "rebuild project",
            "type": "shell",
            "command": "buildscripts/rebuild-debug.sh",
            "args": [],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "presentation": {
                // Reveal the output only if unrecognized errors occur.
                "echo": true,
                "focus": false,
                "reveal": "always",
                "panel": "shared"
            },

            // Use the standard MS compiler pattern to detect errors, warnings and infos
            "options": {
                "cwd": "${workspaceRoot}"
            },
            "problemMatcher": {
                "owner": "cpp",
                "fileLocation": ["relative", "${workspaceRoot}/DEBUG"],
                "pattern": {
                    "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        },
        {
            "label": "clean project",
            "type": "shell",
            "command": "buildscripts/clean-debug.sh",
            "args": [],

            "group": {
                "kind": "build",
                "isDefault": true
            },
            "presentation": {
                // Reveal the output only if unrecognized errors occur.
                "echo": true,
                "focus": false,
                "reveal": "always",
                "panel": "shared"
            },

            // Use the standard MS compiler pattern to detect errors, warnings and infos
            "options": {
                "cwd": "${workspaceRoot}"
            },
            "problemMatcher": {
                "owner": "cpp",
                "fileLocation": ["relative", "${workspaceRoot}/DEBUG"],
                "pattern": {
                    "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        }
    ]
}

Note that, in theory, this file is supposed to work if you put it in the workspace root, so that you aren't stuck checking files in hidden directories (.vscode) into your revision control system. I have yet to see that actually work; test it, but if it fails, put it in .vscode. Either way, the IDE will bitch if it isn't there anyway. (Yes, at the moment, this means I have been forced to check .vscode into subversion, which I'm not happy about.) Note that my build scripts (not shown) simply create (or recreate) a DEBUG directory using, in my case, meson, and build inside it (using, in my case, ninja).

  1. Run, debug, attach, halt. These are another set of tasks, defined in "launch.json". Or at least they used to be. Microsoft has made such a hash of the documentation, I'm not even sure anymore.
Almagest answered 12/3, 2019 at 12:13 Comment(2)
Here'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 $? fiAlmagest
Oh, 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.Almagest
P
6

Here is how I configured my VS for C++ using g++ compiler and it works great including debugging options:

tasks.json file

{
    "version": "0.1.0",
    "command": "g++",
    "isShellCommand": true,
    // compiles and links with debugger information
    "args": ["-g", "-o", "hello.exe", "hello.cpp"],
    // without debugger information
    // "args": ["-o", "hello.exe", "hello.cpp"],
    "showOutput": "always"
}

launch.json file

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "C++ Launch (Windows)",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceRoot}/hello.exe",
            "MIMode": "gdb",
            "miDebuggerPath": "C:\\MinGw\\bin\\gdb.exe",
            "stopAtEntry": false,
            "cwd": "${workspaceRoot}",
            "externalConsole": false,
            "visualizerFile": "${workspaceRoot}/my.natvis"
        }
    ]
}

I also have 'C/C++ for Visual Studio Code' extension installed in VS Code

Platinocyanide answered 17/11, 2016 at 15:37 Comment(1)
I am able to compile, but not debug C/C++ on VSCode. This article says debugging is supported only on linux. Also recently I created this thread for the same. Will appreciate any help...Expertize
T
5

If your project has a CMake configuration it's pretty straight forward to setup VSCode, e.g. setup tasks.json like below:

{
    "version": "0.1.0",
    "command": "sh",
    "isShellCommand": true,
    "args": ["-c"],
    "showOutput": "always",
    "suppressTaskName": true,
    "options": {
        "cwd": "${workspaceRoot}/build"
    },
    "tasks": [
        {
            "taskName": "cmake",
            "args": ["cmake ."]
        },
        {
            "taskName": "make",
            "args" : ["make"],
            "isBuildCommand": true,
            "problemMatcher": {
                "owner": "cpp",
                "fileLocation": "absolute",
                "pattern": {
                    "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        }
    ]
}

This assumes that there is a folder build in the root of the workspace with a CMake configuration.

There's also a CMake integration extension that adds a "CMake build" command to VScode.

PS! The problemMatcher is setup for clang-builds. To use GCC I believe you need to change fileLocation to relative, but I haven't tested this.

Tsarevitch answered 3/9, 2016 at 9:48 Comment(0)
S
5

With an updated VS Code you can do it in the following manner:

  1. Hit (Ctrl+P) and type:
ext install cpptools
  1. Open a folder (Ctrl+K & Ctrl+O) and create a new file inside the folder with the extension .cpp (ex: hello.cpp):

  2. Type in your code and hit save.

  3. Hit (Ctrl+Shift+P and type, Configure task runner and then select other at the bottom of the list.

  4. Create a batch file in the same folder with the name build.bat and include the following code to the body of the file:

@echo off
call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x64     
set compilerflags=/Od /Zi /EHsc
set linkerflags=/OUT:hello.exe
cl.exe %compilerflags% hello.cpp /link %linkerflags%
  1. Edit the task.json file as follows and save it:
{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "0.1.0",
    "command": "build.bat",
    "isShellCommand": true,
    //"args": ["Hello World"],
    "showOutput": "always"
}
  1. Hit (Ctrl+Shift+B to run Build task. This will create the .obj and .exe files for the project.

  2. For debugging the project, Hit F5 and select C++(Windows).

  3. In launch.json file, edit the following line and save the file:

"program": "${workspaceRoot}/hello.exe",
  1. Hit F5.
Sew answered 7/7, 2017 at 21:8 Comment(1)
I'm using the latest VSC. You lost me at Step 4. Configure task runner is not available.Disapprove
H
3

Can use Extension Code Runner to run code with play icon on top Right ans by shortcut key :Ctrl+Alt+N and to abort Ctrl+Alt+M. But by default it only shows output of program but for receiving input you need to follow some steps:

Ctrl+, and then settings menu opens and Extensions>Run Code Configuration scroll down its attributes and find Edit in settings.json click on it and add following code insite it :

{
 "code-runner.runInTerminal": true
}
Hairbreadth answered 17/9, 2019 at 20:7 Comment(2)
Ctrl+ zooms in for meDetroit
it's ctrl comma not ctrl plus to open settingsMores
R
2

You can reference to this latest gist having a version 2.0.0 task for Visual Studio Code, https://gist.github.com/akanshgulati/56b4d469523ec0acd9f6f59918a9e454

You can easily compile and run each file without updating the task. It's generic and also opens the terminal for input entries.

Rote answered 16/11, 2017 at 19:18 Comment(0)
A
0

There's now a C/C++ language extension from Microsoft. You can install it by going to the "quick open" thing (Ctrl+p) and typing:

ext install cpptools

You can read about it here:

https://blogs.msdn.microsoft.com/vcblog/2016/03/31/cc-extension-for-visual-studio-code/

It's very basic, as of May 2016.

Arredondo answered 10/5, 2016 at 19:35 Comment(1)
This is a borderline link-only answer. You should expand your answer to include as much information here, and use the link only for reference.Mcnelly

© 2022 - 2024 — McMap. All rights reserved.