Set up Visual Studio Code for Microsoft C++ (2023)

In this tutorial, you configure Visual Studio code to use the Microsoft Visual C++ compiler and debugger on Windows.

After setting up VS Code, you'll build and debug a simple Hello World program in VS Code. This tutorial does not go into detail about the Microsoft C++ toolset or the C++ language. There are many good resources available on the Internet on these topics.

If you have any problems, you can submit the problem to this tutorial on the siteVS Code documentation repository.

previous requirements

To successfully complete this tutorial, you need to do the following:

  1. installvisual studio code.

  2. installC/C++ extension for VS Code. You can install the C/C++ extension by searching for "c++" in the extensions view (⇧⌘X(Windows, LinuxCtrl+Shift+X)).

    Set up Visual Studio Code for Microsoft C++ (1)

  3. Install the Microsoft Visual C++ Compiler Toolkit (MSVC).

    If you have the latest version of Visual Studio, open the Visual Studio installer from the Windows Start menu and verify that the C++ workload is selected. If it is not installed, check the box and select an optionModifybutton in the installer.

    You can also installCreating desktops in C++workload without a full installation of the Visual Studio IDE. from the visual studioFiles to downloadpage, scroll down until you see itTools for Visual Studiopodall downloadssection and select a file to downloadTool development tools for Visual Studio 2022.

    Set up Visual Studio Code for Microsoft C++ (2)

    This will launch the Visual Studio installer, which will display a dialog box listing the available Visual Studio Build Tools workloads. CheckCreating desktops in C++load and selectinstall.

    Set up Visual Studio Code for Microsoft C++ (3)

Use: You can use the Visual Studio Build Tools C++ together with Visual Studio Code to build, compile, and test any C++ codebase as long as you also have a valid Visual Studio license (Community, Pro, or Enterprise). actively uses to develop the C++ codebase.

Check the installation of Microsoft Visual C++

To use MSVC from the command line or VS Code, you need to run from a fileDeveloper Command Prompt for Visual Studio. A regular shell like PowerShell, Bash, or Windows Command Prompt doesn't have the necessary path environment variables set.

To open the developer command line for VS, start typing "developer" in the Windows start menu and you should see it in the list of suggestions. The exact name depends on which version of Visual Studio or Visual Studio Build Tools you have installed. Select an item to open the message.

Set up Visual Studio Code for Microsoft C++ (4)

You can prove you have a C++ compiler,cl.exe, was successfully installed after typing "cl". You should see a copyright notice with the version and basic usage description.

Set up Visual Studio Code for Microsoft C++ (5)

If your developer command line uses the BuildTools location as your home directory (you don't want to put your projects there), navigate to your user folder (C:\users\{your username}\) before starting new projects.

Use: If for some reason you can't run VS Code from the fileProgrammer's command lineyou can find a workaround to create C++ projects with VS Code atRun VS Code outside the developer command line.

Create Hello World

In the developer command line, create an empty folder called "projects" where you can store all your VS Code projects, then create a subfolder called "helloworld", navigate to it and open VS Code (code) in this folder (.) by typing the following commands:

mkdirProjectsCDProjectsmkdirHello WorldCDHello Worldcode.

code command." opens VS Code in your current working folder, which becomes your "workspace". As you progress through the tutorial, you'll see three files created in.vscodefolder in workspace:

  • tasks.json(building instructions)
  • run.json(debugger settings)
  • c_cpp_properties.json(compiler path and IntelliSense settings)

Add a source code file

In the File Explorer title bar, select an optionnew filebutton and name the filehelloworld.cpp.

Set up Visual Studio Code for Microsoft C++ (6)

Add the Hello World source code

Now paste this source code:

#switch on #switch on #switch on by namespace sexually transmitted disease;and T main(){vectormessage {„Hola”,„C++”,"World","z","Code VS","and C++ extension!"}; Do(constantstring and word: message){cout << word <<" ";}cout<}

now press⌘S(Windows, LinuxCtrl+S)to save the file. Notice how the file you just added appears in the fileFile Browserview (⇧⌘E(Windows, LinuxCtrl+Stream+E)) in the VS Code sidebar:

Set up Visual Studio Code for Microsoft C++ (7)

You can also enableautomatic savingto automatically save changes to the file by checkingautomatic savinggenerallyArchivesmenu.

The activity bar on the left allows you to open different views such asTo look for,control source, jStart. you will look atStartsee later in this tutorial. You can learn more about other views in VS Code.User interface documentation.

Use- When you save or open a C++ file, you may see a notification from the C/C++ extension that an Insiders build is available to test new features and fixes. You can ignore this notification by selecting the optionX(clear notification).

Explore IntelliSense

in your new onehelloworld.cppfile, hover overvectorochainto view type information. After the statementmessagevariable, start typingmessage.just like when you call a member function. You should immediately see a completion list showing all member functions and a window showing type informationmessageobject:

Set up Visual Studio Code for Microsoft C++ (8)

You can pressEyelashkey to insert a selected bar; then, when you add an opening parenthesis, you'll see information about the arguments required by the function.

Run helloworld.cpp

Note that the C++ extension uses the C++ compiler you have installed on your computer to build the program. Make sure you have the C++ compiler installed before attempting to run and debughelloworld.cppcompared to the code.

  1. openhelloworld.cppto make it the active file.

  2. Press the play button in the upper right corner of the editor.

    Set up Visual Studio Code for Microsoft C++ (9)

  3. To chooseC/C++: cl.exe compiles and debugs the active filefrom the list of compilers detected on your system.

    Set up Visual Studio Code for Microsoft C++ (10)

You will only be asked to select a compiler on first runhelloworld.cpp. This compiler will be set as the "default" compiler intasks.jsonarchives.

  1. After successful compilation, the output of the program will appear in the embedded file.Terminal.

    Set up Visual Studio Code for Microsoft C++ (11)

If you get an error when trying to compile and debug with cl.exe, make sure it doesI ran VS Code from the developer command line for Visual Studiousingcode.abbreviation.

Set up Visual Studio Code for Microsoft C++ (12)

The C++ extension is created the first time the program is runtasks.jsonwhich you will find in your project directory..vscodefile.tasks.jsonholds build configurations.

your newtasks.jsonThe file should look similar to the JSON below:

{ "version":„2.0.0”, "tasks": [{ "typ":"shell", "label":"C/C++: cl.exe creates active file", "domain":„cl.exe”, „argos”: [ "/Day", „/EHsc”, „/Fe:”, "${filename}\\${fileBasenameNoExtension}.exe”, "${file}"], "Problem Matches": [„$msCompilar”], "Group": { "delicate":"build", "is the default":TRUE}, "Detail":"Job generated by the debugger."}]}

Use: You can learn more abouttasks.jsonvariables invariable reference.

Ondomainconfiguration specifies the program to run; in this case it is "cl.exe". HeargumentsThe array specifies the command line arguments to be passed to cl.exe. These arguments must be specified in the order expected by the compiler.

This task tells the C++ compiler to download the active file (${file}), compile it and create an executable (/Fe:change) in the current directory (${filename}) with the same name as the active file, but with the extension.exeextension (${fileBasenameNoExtension}.exe), as a resultholamundo.exefor our example.

Onlabelthe value is the one you will see in the task list; you can call it what you want.

OnDetailThis value will be used as the job description in the job list. It is strongly recommended that you rename this value to distinguish it from similar tasks.

OnproblemMatchervalue selects the output parser that will be used to check for errors and warnings in the compiler output. For cl.exe, you'll get the best results if you use$msCompilartroublesome matches.

From then on, the play button will readtasks.jsonto learn how to compile and run the program. You can define multiple build tasks intasks.json, and all tasks marked as default will be used by the play button. If you want to change the default compiler, you can runTasks: Set the default build task. Alternatively, you can modify the filetasks.jsonfile and remove the default by replacing this segment:

 "Group": { "delicate":"build", "is the default":TRUE},

with this:


Modifying the task.json file

you can modify yourstasks.jsonto build multiple C++ files using a single argument, e.g"${workspaceFolder}/*.cpp"rather${file}This will build everything.cppfiles in the current folder. You can also modify the name of the output file by replacing it„${fileDirname}\\${fileBasenameNoExtension}.exe”with an encoded filename (eg„${workspaceFolder}\\myProgram.exe”).

Remove helloworld.cpp

To debug your code,

  1. Come back tohelloworld.cppto make it the active file.
  2. Set a breakpoint by clicking in the editor margin or using the F9 key on the current line.Set up Visual Studio Code for Microsoft C++ (13)
  3. Select from the drop-down menu next to the play buttonDebug a C/C++ file.Set up Visual Studio Code for Microsoft C++ (14)
  4. To chooseC/C++: cl.exe compiles and debugs the active filefrom the list of compilers detected on your system (you will only be asked to select a compiler on first run or debugging)helloworld.cpp).Set up Visual Studio Code for Microsoft C++ (15)

The play button has two modes:Execute a C/C++ fileyDebug a C/C++ file. By default, the last used mode will be used. If you see a debug icon on the play button, you can select the play button to debug instead of selecting the drop-down menu item.

If you get an error when trying to compile and debug with cl.exe, make sure it doesI ran VS Code from the developer command line for Visual Studiousingcode.abbreviation.

Set up Visual Studio Code for Microsoft C++ (16)

Meet the debugger

Before we start looking at the code, let's take a moment to notice a few UI changes:

  • The integrated terminal will appear at the bottom of the source code editor. Includingdebug output, you'll see output indicating that the debugger is running.

  • The editor highlights the line where you set a breakpoint before starting the debugger:

    Set up Visual Studio Code for Microsoft C++ (17)

  • Onrun and debugThe view on the left shows debugging information. You'll see an example later in the tutorial.

  • A debug control panel appears at the top of the code editor. It can be moved around the screen by grabbing the dots on the left side.

    Set up Visual Studio Code for Microsoft C++ (18)

go through the code

You can now start reviewing the code.

  1. Click or tapovericon in the debug control panel.

    Set up Visual Studio Code for Microsoft C++ (19)

    This will speed up program execution to the first line of the for loop and skip all internal function calls in the loop.vectorychainclasses that are called whenmessageThe variable is created and initialized. Note the change invariableslive okno

    Set up Visual Studio Code for Microsoft C++ (20)

    Expect errors in this case, because while the names of the loop variables are now visible to the debugger, the statement hasn't been executed yet, so there's nothing to read at the moment. Contentsmessagehowever, they are visible because the statement has been supplemented.

  2. Pressoveragain to go to the next statement in that program (skipping all the internal code executed to initialize the loop). now himvariablesThe window displays information about the loop variables.

  3. Pressoveragain to runcuttingstatement. (Note that as of the March 2019 release, the C++ extension does not print any output to a filedebug consoleuntil the end of the loop).

  4. You can keep pressing if you wantoveruntil all the words of the vector are printed to the console. But if you are curious, try pressingenterA button to browse the source code in the C++ Standard Library!

    Set up Visual Studio Code for Microsoft C++ (21)

    To go back to your own code, one way is to keep pressingover. Another way is to set a breakpoint in your code by changing tohelloworld.cppin the code editor, placing the insertion point somewhere in the filecuttingstatement inside the loop and pressingF9. A red dot will appear in the left margin, indicating that a breakpoint has been set on that line.

    Set up Visual Studio Code for Microsoft C++ (22)

    then pressF5to start execution from the current line in the standard library header. The execution will be stoppedcutting. You can press if you wantF9again to disable the breakpoint.

Set your watch

Sometimes you may want to track the value of a variable while the program is running. You can do this by setting aLookabout the variable.

  1. Place the insertion point inside the loop. IncludingLookselect the plus sign and enter in the text boxword, which is the name of the loop variable. Now see the Watch window as you go through the loop.

    Set up Visual Studio Code for Microsoft C++ (23)

  2. Add another watch by adding this statement before the loop:int you = 0;. Then inside the loop add the following statement:++yo;. Now add a clock forIas you did in the previous step.

  3. To quickly see the value of any variable when execution is paused at a breakpoint, you can hover over it.

    Set up Visual Studio Code for Microsoft C++ (24)

Customize debugging with launch.json

When debugging with the play or buttonF5, the C++ extension creates a dynamic debug configuration on the fly.

In some cases, you'll need to adjust your debug configuration, such as specifying the arguments passed to your program at runtime. You can define custom debug configurations in a filerun.jsonarchives.

Createrun.json, to chooseAdd a debug configurationfrom the play button drop-down menu.

Set up Visual Studio Code for Microsoft C++ (25)

Then you will see a drop-down menu with various predefined debug configurations. To chooseC/C++: cl.exe compiles and debugs the active file.

Set up Visual Studio Code for Microsoft C++ (26)

VS Code creates the filerun.jsona file that looks like this:

{ "version":„0.2.0”, "settings": [{ "name":"C/C++: cl.exe is compiling and debugging the active file", "typ":„cppvsdbg”, "order":"beginning", "program":"${filename}\\${fileBasenameNoExtension}.exe”, „argos”: [], "stop at the entrance":FALSEHOOD, „cwd”:"${workspace folder}", "environment": [], "external console":FALSEHOOD, "Pre-Launch Task":"C/C++: cl.exe creates active file"}]}

In the above JSONprogramspecifies the program you want to debug. Here it is set to the active file folder (${filename}) and the active file name with the extension.exeextension (${fileBasenameNoExtension}.exe), Sohelloworld.cppwill be the active fileholamundo.exe. OnargumentsThe property is a series of arguments passed to the program at run time.

By default, the C++ extension will not add any breakpoints to your source code, and thestop at the entrancethe value is set toFALSEHOOD.

To changestop at the entrancebravery aTRUEto make the debugger stop atmainmethod after starting debugging.

From now on, the play button iF5I will read from himrun.jsonfile when starting the program to debug it.

C/C++ configurations

If you want more control over the C/C++ extension, you can create ac_cpp_properties.jsonfile that will allow you to change settings such as compiler path, include paths, C++ standard (default is C++17) and more.

You can view the C/C++ Configuration UI by running the commandC/C++: Edit Settings (UI)from the command palette (⇧⌘P(Windows, LinuxCtrl+Shift+P)).

Set up Visual Studio Code for Microsoft C++ (27)

It opensC/C++ configurationsside. When you make changes here, VS Code saves them to a file calledc_cpp_properties.jsonincluding.vscodefile.

Set up Visual Studio Code for Microsoft C++ (28)

Visual Studio Code places these settings in.vscode\c_cpp_properties.json. If you open this file directly, it should look like this:

{ "settings": [{ "name":“Win32”, "include route": [„${workspaceFolder}/**”], "define": ["_DEBUG",„UNICODIO”,„_UNICODE”], "Windows SDK Version":„10.0.18362.0”, "compiler path":"C:/Program Archives (x86)/Microsoft Visual Studio/2019/BuildTools/VC/Tools/MSVC/14.24.28314/bin/Hostx64/x64/cl.exe", "cStandard":"c11", „cppStandard”:„c++17”, „tryb IntelliSense”:„msvc-x64”}], "version":4}

You just need to addinclude patharray configuration if the program contains header files that are not in the workspace or standard library path.

compiler path

Oncompiler pathSettings are important settings in configuration. The extension uses it to infer the path to the C++ Standard Library header files. Once the extension knows where to find these files, it can provide useful features such as smart completion andGo to definitionnavigation.

Attempting to terminate a C/C++ extensioncompiler pathwith the default compiler location based on what it finds on your system. The extension looks in several popular compiler locations.

Oncompiler paththe search order is:

  • First check the Microsoft Visual C++ compiler.
  • Then search for g++ in Windows Subsystem for Linux (WSL)
  • Then g++ for Mingw-w64.

If you have g++ or WSL installed, you may need to change itcompiler pathto match your preferred compiler for your project. For Microsoft C++, the path should be as follows, depending on the specific version installed: "C:/Program Files (x86)/Microsoft Visual Studio/2017/BuildTools/VC/Tools/MSVC/14.16.27023/bin/Hostx64/x64/ cl.exe”.

Reusing C++ configuration

VS Code is now configured to use the Microsoft C++ compiler. The settings will be applied to the current workspace. To reuse the configuration, just copy the JSON files to a file.vscodefolder to your new project (workspace) folder and rename your source files and executables as needed.

Run VS Code outside the developer command line

Under certain circumstances, it is not possible to run VS CodeDeveloper Command Prompt for Visual Studio(for example, for remote development using SSH scenarios). In this case, you can automate the initializationDeveloper Command Prompt for Visual Studioduring compilation using the followingtasks.jsonsetting:

{ "version":„2.0.0”, "windows": { "options": { "shell": { "executable":„cmd.exe”, „argos”: [ "/C", // The path to the VsDevCmd.bat file depends on the version of Visual Studio you have installed. "\"C:/Archivos de programa (x86)/Microsoft Visual Studio/2019/Community/Common7/Tools/VsDevCmd.bat\"", „&&”]}}}, "tasks": [{ "typ":"shell", "label":"cl.exe creates active file", "domain":„cl.exe”, „argos”: [ "/Day", „/EHsc”, „/Fe:”, "${filename}\\${fileBasenameNoExtension}.exe”, "${file}"], "Problem Matches": [„$msCompilar”], "Group": { "delicate":"build", "is the default":TRUE}}]}

Use: The way toVsDevCmd.batmay vary depending on Visual Studio version or installation path. You can find a way toVsDevCmd.batopen command line and runkatalog "\VsDevCmd*" /s.


The term "cl.exe" is not recognized

If you see the error "The term 'cl.exe' is not recognized as the name of a cmdlet, function, script file or executable program", it usually means that you are using VS Code outside of your environmentDeveloper Command Prompt for Visual Studioand VS Code doesn't know the path tocl.execompiler.

VS Code must be launched from the developer command line for Visual Studio or the task must be set uprun outside the developer command line.

You can always check if you are using VS Code in the context of the developer command line by opening a new terminal (⌃⇧`(Windows, LinuxCtrl+Shift+`)) and type "cl" to checkcl.exeis available for VS Code.

fatal error C1034:theorem.h: Include path not set

In this case,cl.exeis available for VS Code viaCHIMNEYenvironment variable, but VS Code still needs to be run from withinDeveloper Command Prompt for Visual Studioor set torun outside developer command line. Otherwise,cl.exedoes not have access to important environment variables such asSWITCH ON.

Next steps

  • exploreVS Code User Guide.
  • CheckOverview of the C++ extension.
  • Create a new workspace, copy yours.vscodeJSON, adjust the necessary settings for the new workspace path, program name, etc. and start coding!



Top Articles
Latest Posts
Article information

Author: Barbera Armstrong

Last Updated: 08/29/2023

Views: 5861

Rating: 4.9 / 5 (59 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Barbera Armstrong

Birthday: 1992-09-12

Address: Suite 993 99852 Daugherty Causeway, Ritchiehaven, VT 49630

Phone: +5026838435397

Job: National Engineer

Hobby: Listening to music, Board games, Photography, Ice skating, LARPing, Kite flying, Rugby

Introduction: My name is Barbera Armstrong, I am a lovely, delightful, cooperative, funny, enchanting, vivacious, tender person who loves writing and wants to share my knowledge and understanding with you.