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:
installvisual studio code.
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)).
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.
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.
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.
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.
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.vscode
folder 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
.
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:
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 option
X
(clear notification).
Explore IntelliSense
in your new onehelloworld.cpp
file, hover overvector
ochain
to view type information. After the statementmessage
variable, 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 informationmessage
object:
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.cpp
compared to the code.
open
helloworld.cpp
to make it the active file.Press the play button in the upper right corner of the editor.
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 runhelloworld.cpp
. This compiler will be set as the "default" compiler intasks.json
archives.
After successful compilation, the output of the program will appear in the embedded file.Terminal.
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.
The C++ extension is created the first time the program is runtasks.json
which you will find in your project directory..vscode
file.tasks.json
holds build configurations.
your newtasks.json
The 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 about
tasks.json
variables invariable reference.
Ondomain
configuration specifies the program to run; in this case it is "cl.exe". Hearguments
The 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.exe
extension (${fileBasenameNoExtension}.exe
), as a resultholamundo.exe
for our example.
Onlabel
the value is the one you will see in the task list; you can call it what you want.
OnDetail
This 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.
OnproblemMatcher
value 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$msCompilar
troublesome matches.
From then on, the play button will readtasks.json
to 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.json
file and remove the default by replacing this segment:
"Group": { "delicate":"build", "is the default":TRUE},
with this:
"Group":"build",
Modifying the task.json file
you can modify yourstasks.json
to build multiple C++ files using a single argument, e.g"${workspaceFolder}/*.cpp"
rather${file}
This will build everything.cpp
files 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,
- Come back to
helloworld.cpp
to make it the active file. - Set a breakpoint by clicking in the editor margin or using the F9 key on the current line.
- Select from the drop-down menu next to the play buttonDebug a C/C++ file.
- 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
).
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.
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:
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.
go through the code
You can now start reviewing the code.
Click or tapovericon in the debug control panel.
This will speed up program execution to the first line of the for loop and skip all internal function calls in the loop.
vector
ychain
classes that are called whenmessage
The variable is created and initialized. Note the change invariableslive oknoExpect 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. Contents
message
however, they are visible because the statement has been supplemented.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.
Pressoveragain to run
cutting
statement. (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).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!
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 to
helloworld.cpp
in the code editor, placing the insertion point somewhere in the filecutting
statement inside the loop and pressingF9. A red dot will appear in the left margin, indicating that a breakpoint has been set on that line.then pressF5to start execution from the current line in the standard library header. The execution will be stopped
cutting
. 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.
Place the insertion point inside the loop. IncludingLookselect the plus sign and enter in the text box
word
, which is the name of the loop variable. Now see the Watch window as you go through the loop.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 forI
as you did in the previous step.To quickly see the value of any variable when execution is paused at a breakpoint, you can hover over it.
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.json
archives.
Createrun.json
, to chooseAdd a debug configurationfrom the play button drop-down menu.
Then you will see a drop-down menu with various predefined debug configurations. To chooseC/C++: cl.exe compiles and debugs the active file.
VS Code creates the filerun.json
a 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 JSONprogram
specifies the program you want to debug. Here it is set to the active file folder (${filename}
) and the active file name with the extension.exe
extension (${fileBasenameNoExtension}.exe
), Sohelloworld.cpp
will be the active fileholamundo.exe
. Onarguments
The 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 entrance
the value is set toFALSEHOOD
.
To changestop at the entrance
bravery aTRUE
to make the debugger stop atmain
method after starting debugging.
From now on, the play button iF5I will read from him
run.json
file 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.json
file 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)).
It opensC/C++ configurationsside. When you make changes here, VS Code saves them to a file calledc_cpp_properties.json
including.vscode
file.
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 path
Settings 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 path
with the default compiler location based on what it finds on your system. The extension looks in several popular compiler locations.
Oncompiler path
the 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 path
to 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.vscode
folder 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.json
setting:
{ "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 to
VsDevCmd.bat
may vary depending on Visual Studio version or installation path. You can find a way toVsDevCmd.bat
open command line and runkatalog "\VsDevCmd*" /s
.
Troubleshooting
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.exe
compiler.
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.exe
is available for VS Code.
fatal error C1034:theorem.h: Include path not set
In this case,cl.exe
is available for VS Code viaCHIMNEY
environment variable, but VS Code still needs to be run from withinDeveloper Command Prompt for Visual Studioor set torun outside developer command line. Otherwise,cl.exe
does 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
.vscode
JSON, adjust the necessary settings for the new workspace path, program name, etc. and start coding!
3.7.2023