In this tutorial, you will configure Visual Studio Code to use the GCC C++ (g++) compiler and the GDB debugger.mingw-w64to create programs that run under Windows.
After setting up VS Code, compile and debug a simple "Hello World" program in VS Code. This tutorial does not cover GCC, GDB, Mingw-w64, or the C++ language. There are many good resources on the Internet for these matters.
If you encounter any problems, you can report a problem for this tutorial atVS Code-documentation repository.
requirements
In order to successfully complete this tutorial, you must complete the following steps:
installvisual studio code.
install thatC/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)).
Get the latest version of mingw-w64MSYS2, which provides current native builds of GCC, Mingw-w64, and other useful C++ tools and libraries. You can download or use the latest installer from the MSYS2 sitelink to installer.
follow thatInstallationinstructions on theMSYS2 Locationto install Mingw-w64. Be sure to run any necessary start menus and
pac-man
Domain.Install the mingw-w64 toolchain (
pacman -S --necesita base-devel mingw-w64-x86_64-toolchain
). run orpac-man
command in an MSYS2 terminal. Accept the default to install all membersToolbox
Group.Add the path to your mingw-w64
container
get for windowsFAR
environment variable with the following steps:- Type "settings" in the Windows search bar to open Windows settings.
- Look forEdit environment variables for your account.
- Select the
Far
variable in youruser variablesand then selectTo edit. - choosenuevoand add the mingw-w64 destination folder path to the system path. The exact path depends on what version of Mingw-w64 you have installed and where you have installed it. If you used the above configuration to install mingw-w64, add this to the path:
C:\msys64\mingw64\bin
. - chooseOKto save the updated PATH. You must reopen all console windows for the new PATH location to be available.
Verify the MinGW installation
To verify that your mingw-w64 tools are correctly installed and available, open anuevocommand prompt and type:
gcc --versiong++ --versiongdb --version
- If you don't see the expected result or
g ++
ogdb
is not a recognized command, make sure your PATH entry matches the mingw-w64 binary location where the compilers reside. If the compilers are not present in this PATH entry, be sure to follow the instructions inMSYS2 Locationto install Mingw-w64. - Se
CCG
has the correct output, but nogdb
, then you need to install the missing packages in the mingw-w64 toolset.- missing the
mingw-w64-gdb
The packet is one of the causes of "The value of myDebuggerPath is invalid". Message when trying to compile if your PATH is correct.
- missing the
create hello world
At a Windows command prompt, create an empty folder namedProjects
where you can put all your VS Code projects. Then create a subfolder calledHello World
, navigate there and open VS Code in that folder by typing the following commands:
mkdirProjectsCDProjectsmkdirHello WorldCDHello Worldcode
The code ." command opens VS Code in the current working folder, which becomes your "workspace".Workspace Trustselect dialogYes, I trust the authors.because this is a folder that you created.
As you progress through the tutorial, you will see three files created in one.vscode
Folders on the desktop:
Tasks.json
(Building Instructions)launch.json
(Debugger Settings)c_cpp_properties.json
(compiler path and intellisense configuration)
Add a source code file
In the File Explorer title bar, select thenew filebutton and file namehallowelt.cpp
.
Add hello world source code
Now paste this source code:
#contain <iostream>#contain <Vector>#contain <string>to use namespace Standard;And t Principal(){vector<string> message {"Hola","C++","Bump","von","VS-Code","and the C++ extension!"}; for(untilstring and word: message){cout << must <<" ";}cout << endl;}
press now⌘S(Windows,LinuxStrg+S)to save the file. Notice how the file you just added appears in thefile managerver (⇧⌘E(Windows,LinuxCtrl+Mayus+E)) in the VS Code sidebar:
You can also activateauto saveto automatically save changes to the file by checking the boxauto savenot mainarchiveMenu.
You can open different views via the activity bar on the far left, e.g.Look for,control source, zRun. you will look at themRunsee later in this tutorial. You can learn more about the other views of VS CodeUser interface documentation.
supervision: When you save or open a C++ file, you might see a notification from the C/C++ extension about the availability of an Insiders build that you can use to test new features and fixes. You can ignore this notification by selecting that
X
(clear notification).
Discover IntelliSense
in your newhallowelt.cpp
file, hover over itVector
orope
to view type information. After the explanation ofNews
Variable, start typingNews.
just like you would when calling a member function. You should immediately see a complete list showing all member functions and a window with the type information forNews
Object:
You can press thoseababutton to paste the selected member; If you then add the opening parenthesis, you'll see information about all the arguments the function takes.
Run helloworld.cpp
Remember that the C++ extension uses the C++ compiler that you have installed on your computer to create your program. Make sure you have a C++ compiler installed before trying to run and debug it.hallowelt.cpp
not VS code.
Open
hallowelt.cpp
to make it the active file.Hit the play button in the top right corner of the editor.
ChooseC/C++: g++.exe builds and debugs the active filefrom the list of compilers detected on your system.
You will only be asked to choose a compiler the first time you run ithallowelt.cpp
. This compiler will be set as the "default" compiler inTasks.json
Archive.
After a successful compilation, the output of your program appears in the insertTerminal.
When you run your program for the first time, the C++ extension createsTasks.json
What will you find in your project?.vscode
Pasta.Tasks.json
save the build configuration.
your newTasks.json
The file should resemble the following JSON:
{ "Tasks": [{ "Type":"cppconstruct", "Label":"C/C++: g++.exe creates an active file", "Domain":"C:\\msys64\\mingw64\\container\\g++.exe", "arg": [ "-fdiagnostics-color=immer", "-GRAMS", "${file}", "-Ö", "${archivoDirname}\\${baseFileNameWithoutExtension}.exe"], "options": { "cwd":"${archivoDirname}"}, "Correspondent Problem": ["$gcc"], "Group": { "Type":"build", "is default":TRUE}, "Detail":"Task generated by debugger."}], "Execution":"2.0.0"}
supervision: You can learn more about it
Tasks.json
Variablesvariable reference.
odomain
the configuration specifies the program to run; in this case it is g++.argument
array specifies the command line arguments passed to g++. These arguments must be specified in the order expected by the compiler.
This task tells g++ to find the active file (${file}
), compile it, and create an executable in the current directory (${archivoDirname}
) with the same name as the active file but with the extension.exe
renovation (${fileBasenameNoExtension}.exe
), resultingholamundo.exe
for our example.
olabel
the value is what you see in the task list; you can name it whatever you want.
oDetail
The value is what you want as the description of the task in the task list. We strongly recommend renaming this value to distinguish it from similar tasks.
As of now, the play button saysTasks.json
to find out how to build and run your program. You can define multiple build tasks inTasks.json
, and any tasks marked as default will be used by the play button. If you need to change the default compiler, you can run itTasks: Set the default build task. Alternatively, you can change itTasks.json
Archive and remove the default by replacing this segment:
"Group": { "Type":"build", "is default":TRUE},
For this reason:
"Group":"build",
Modify the tasks.json file.
you can change yoursTasks.json
to create multiple C++ files with one argument like"${workspace folder}/*.cpp"
rather${file}
.which will build everything.cpp
files in your current folder. You can also rename the output file by replacing"${fileDirname}\\${fileBasenameNoExtension}.exe"
with an encrypted filename (eg."${working folder}\\myprogram.exe"
).
Limpiar helloworld.cpp
- times for
hallowelt.cpp
to make it the active file. - Set a breakpoint by clicking on the editor border or by using F9 on the current line.
- Select from the dropdown menu next to the play buttonDebugging C/C++ files.
- ChooseC/C++: g++ compiles and debugs the active filefrom the list of compilers detected on your system (you will only be asked to select a compiler the first time you run/debug it)
hallowelt.cpp
).
The play button has two modes:Run the C/C++ filemiDebugging C/C++ files. The default is the last used mode. If you see the debug icon on the play button, just click the play button to debug instead of using the dropdown.
explore the debugger
Before we start walking through the code, let's look at some UI changes:
The built-in terminal is shown below in the source code editor. In itdebug outputtab, you will see output indicating that the debugger is working.
The editor highlights the line where you set a breakpoint before starting the debugger:
orun and debugThe preview on the left shows debugging information. You'll see an example later in the tutorial.
A debug panel appears at the top of the code editor. You can move it around the screen by holding down the dots on the left.
step through code
Now you can start stepping through the code.
Click or press the buttonget over itIcon in the Debugging Control Panel.
This moves program execution to the first line of the for loop and skips any internal function calls inside the for loop.
Vector
mirope
Classes that are called when theNews
Variable created and initialized. Notice the change inVariablesleft window.In this case, errors are expected because although the loop variable names are now visible to the debugger, the statement has not yet been executed, so there is nothing to read at this point. content
News
they are visible, however, since this statement is complete.Pressget over itagain to get to the next statement in that program (skipping all the internal code that is executed to initialize the loop). Now himVariablesThe window displays information about the loop variables.
Pressget over itrun again
cout
Explanation. (Note that as of the March 2019 release, the C++ extension is not shipped to theconsole debugginguntil the loop ends.)If you want, you can keep pressingget over ituntil all the words in the array have been printed to the console. But if you're curious, try pressing the buttonGet intoButton to walk through the source code in the C++ standard library!
To return to your own code, you can hold down the buttonget over it. Another option is to set a breakpoint in your code and change
hallowelt.cpp
Guide in the code editor, place the insertion point somewhere in thecout
instruction inside the loop and pressF9. A red dot appears in the left margin to indicate that a breakpoint has been set on that line.then pressF5to start execution from the current line in the standard library header. execution is stopped
cout
. If you want, you can pressF9again to disable the breakpoint.When the loop is complete, you can see the output in the embedded terminal along with other diagnostic information generated by GDB.
set a clock
Sometimes you may want to keep track of the value of a variable while your program is running. You can do this by defining ato participatein variable.
Place the insertion point inside the loop. In itTo participateIn the window, click the plus sign and type in the text box
must
, which is the name of the loop variable. Now watch the clock window as you go through the loop.Add another watch by adding this statement before the loop:
int i = 0;
. Then inside the loop add this statement:++I;
. now add a clockUE
as in the previous step.To quickly see the value of any variable while execution is paused at a breakpoint, you can hover over it.
Customize debugging with launch.json
When debugging with the play buttonF5the C++ extension creates a dynamic real-time debugging configuration.
There are cases where you want to customize your debugging configuration, e.g. B. specifying arguments that are passed to the program at run time. You can define custom debug configurations in alaunch.json
Archive.
Createlaunch.json
, chooseAdd debug configurationin the play button dropdown menu.
You will see a dropdown menu for several predefined debugging configurations. ChooseC/C++: g++.exe builds and debugs the active file.
VS Code creates alaunch.json
file that looks like this:
{ "Execution":"0.2.0", "Ideas": [{ "Name":"C/C++: Compile and debug live file g++.exe", "Type":"cppdbg", "Consultation":"to throw", "Program":"${archivoDirname}\\${baseFileNameWithoutExtension}.exe", "arg": [], "stop at the entrance":INCORRECT, "cwd":"${archivoDirname}", "Surroundings": [], "external console":INCORRECT, "IM mode":"gdb", "miDebuggerPfad":"C:\\msys64\\mingw64\\container\\gdb.exe", "Configuration Commands": [{ "Description":"Enable pretty printing for gdb", "Text":"-enable-pretty-printing", "Ignore errors":TRUE}], "pre-launch task":"C/C++: g++.exe creates an active file"}]}
In the JSON above,program
specifies the program that you want to debug. Here it will point to the active files folder (${archivoDirname}
) and the name of the active file with the.exe
renovation (${fileBasenameNoExtension}.exe
), Hehallowelt.cpp
is the active fileholamundo.exe
. oargument
The property is an array of arguments that are passed to the program at run time.
By default, the C++ extension does not add breakpoints to its source code, and thestop at the entrance
The value is defined asINCORRECT
.
change thatstop at the entrance
value forTRUE
to make the debugger stopPrincipal
method when you start debugging.
From now on the play button andF5i will read about you
launch.json
file when you start your program for debugging.
C/C++ Configuration
If you want more control over the C/C++ extension, you can use ac_cpp_properties.json
file that allows you to change settings like compiler path, include paths, default C++ (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 (⇧⌘S(Windows,LinuxCtrl+Shift+P)).
This opens theC/C++ Configurationbook page. If you make changes here, VS Code writes them to a file calledc_cpp_properties.json
NO.vscode
Pasta.
Here we change themconfiguration nameforCCG, Put thatcompiler pathDropdown menu for g++ and compilersIntelliSense modematching the compiler (gcc-x64).
Visual Studio Code injects this configuration.vscode\c_cpp_properties.json
. If you open this file directly, it should look like this:
{ "Ideas": [{ "Name":"CCG", "includePfad": ["${workbook}/**"], "define": ["_DEPURACIÓN","UNICODE","_UNICODE"], "WindowsSDkVersion":"10.0.18362.0", "CompiladorPfad":"C:/msys64/mingw64/bin/g++.exe", "cPredetermined":"c17", "cppStandard":"c++17", "intelliSense mode":"ventanas-gcc-x64"}], "Execution":4}
you just have to addadd routeArray configuration if your program contains header files that are not in your workspace or standard library path.
compiler path
The extension uses thecompiladorPath
to derive the path to the C++ Standard Library header files. If the extension knows where to find these files, it can use features like smart completion andgo to definitionNavigation.
The C/C++ extension tries to fillcompiladorPath
with the default compiler location based on what it finds on your system. The extension looks in several common compiler locations.
ocompiladorPath
The search order is:
- First check the Microsoft Visual C++ compiler
- Next, get g++ without Windows Subsystem for Linux (WSL).
- So g++ for Mingw-w64.
If you have Visual Studio or WSL installed, you may need to make changescompiladorPath
matching the preferred compiler for your project. For example, if you installed Mingw-w64 version 8.1.0 with the i686 architecture, Win32 threads, and sjlj exception handling install options, the path would look like this:C:\Arquivos de Programas (x86)\mingw-w64\i686-8.1.0-win32-sjlj-rt_v6-rev0\mingw64\bin\g++.exe
.
Troubleshooting
MSYS2 is installed but g++ and gdb still not found
you have to follow the stepsMSYS2 Locationand use MSYS CLI to install Mingw-w64 which contains these tools. You also need to install the full mingw-w64 toolchain (pacman -S --necesita base-devel mingw-w64-x86_64-toolchain
) to get thatgdb
Washing machine.
MinGW de 32 bits
If you need a 32-bit version of the MinGW toolset, please read theDownloadingon the MSYS2 wiki. Contains links to 32-bit and 64-bit installation options.
Next steps
- explore theVS Code User Guide.
- Check theC++ Extensions Overview.
- Create a new workspace, copy yours
.vscode
JSON, adjust the necessary settings for the new workspace path, program name, etc. and start coding!
13.05.2022