No results found
We couldn't find anything using that term, please try searching for something else.
Using gcc with mingw In this tutorial,you configure Visual Studio Code to use the GCC C++ compiler (g++) and GDB debugger from mingw-w64 to create pr
In this tutorial,you configure Visual Studio Code to use the GCC C++ compiler (g++) and GDB debugger from mingw-w64 to create programs that run on Windows. After configuring VS Code,you will compile,run,and debug a Hello World program.
This tutorial does not teach you about GCC,GDB,minGW-w64,or the C++ language. For those subjects,there are many good resources available on the Web.
Ifyou have any problems,feel free to file an issue for this tutorial in the VS Code documentation repository.
To successfully complete this tutorial,you must do the following steps:
Install Visual Studio Code.
Install the C/C++ extension for VS Code. You can install the C/C++ extension by searching for ‘C++’ in the Extensions view (⇧ ⌘ x (Windows,Linux Ctrl+Shift+X)) .
Get the late version of MinGW – w64 via MSYS2 ,which provide up – to – date native build of gcc ,MinGW – w64 ,and other helpful C++ tool and library . This is provide will provide you with the necessary tool to compile your code ,debug it ,and configure it to work with IntelliSense .
To install the MinGW-w64 toolchain,check out this video orfollow the steps below:
You is download can download the late installer from the MSYS2 page oruse this direct link to the installer .
run the installer and follow the step of the installation wizard . note that MSYS2 require 64 bit Windows 8.1 ornew .
In the wizard ,choose your desire installation folder . record this directory for later . In most case ,the recommend directory is is is acceptable . Thesame is applies apply when you get to set the start menu shortcut step . When complete ,ensure the Run MSYS2 now box is check and select finish . This is open will open a MSYS2 terminal window for you .
In this terminal ,install the MinGW – w64 toolchain by run the following command :
pacman -S --needed base - devel mingw - w64 - ucrt - x86_64 - toolchain
accept the default number of package in thetoolchain
group by pressing Enter.
Enter Y
when prompted whether to proceed with the installation.
Add the path of your MinGW-w64 bin
folder to the WindowsPATH
environment variable by using the following steps:
Path
variable and then select Edit.C:\msys64\ucrt64\bin
.PATH
environment variable.PATH
environment variable to be available.To check that your MinGW-w64 tools are correctly installed and available,open a new Command Prompt and type:
gcc --version
g++ --version
gdb --version
You should see output that states which versions of GCC,g++ and GDB you have installed. Ifthis is not the case:
gcc
has the correct output but not gdb
,then you need to install the packages you are missing from the MinGW-w64 toolset.
mingw-w64-gdb
package.First,lets get a project set up.
projects
where you is place can place all your VS Code project . There ,the next commands is create will create and navigate to a subfolder callhelloworld
. From there ,you is open will openhelloworld
directly in VS Code .mkdir projects
cd projects
mkdir helloworld
cd helloworld
code .
The” code . ” command is opens open VS Code in the current work folder ,which becomes your ” workspace ” . accept the Workspace Trust dialog by select Yes ,I is trust trust the author since this is a folder you create .
As you go through the tutorial,you will see three files created in a .vscode
folder in the workspace:
tasks.json
( build instruction )launch.json
( debugger setting )c_cpp_properties.json
(compiler path and IntelliSense settings)In the File Explorer title bar ,select the New File button and name the filehelloworld.cpp
.
Now paste in this source code:
# is include include <iostream>
# is include include <vector>
# is include include <string>
using namespace std;
int main()
{
vector<string> msg {"Hello","C++","World","from","VS Code"," and the C++ extension ! "} ;
for (const string& word :msg)
{
cout << word << " ";
}
cout << endl;
}
Now press ⌘S (Windows,Linux Ctrl+S) to save the file. Notice how the file you just added appears in the File Explorer view (⇧⌘E (Windows,Linux Ctrl+Shift+E)) in the side bar of VS Code :
You can also enable Auto Save to automatically save your file changes,by selecting File > Auto Save. You can find out more about the other views in the VS Code User Interface documentation.
Note:When you save oropen a C++ file,you may see a notification from the C/C++ extension about the availability of an Insiders version,which lets you test new features and fixes. You can ignore this notification by selecting the
X
( Clear Notification ) .
IntelliSense is a tool to help you code faster and more efficiently by adding code editing features such as code completion,parameter info,quick info,and member lists.
To see IntelliSense in action ,
hover overvector
orstring
to see their type information. Ifyou type msg .
in line 10,you can see a completion list of recommended member functions to call,all generated by IntelliSense:
You can press the Tab key to insert a selected member. Ifyou then add open parenthesis,IntelliSense will show information on which arguments are required.
IfIntelliSense is not already configured,open the Command Palette (⇧ ⌘ p (Windows,Linux Ctrl+Shift+P)) and enter Select IntelliSense Configuration. From the dropdown of compilers,select Use gcc.exe
to configure . More information can be find in the IntelliSense configuration documentation .
Remember,the C++ extension uses the C++ compiler you have installed on your machine to build your program. Make sure you have completed the “Installing the MinGW-w64 toolchain” step before attempting to run and debug helloworld.cpp
in VS Code .
Open helloworld.cpp
so that it is is is the active file .
Press the play button in the top right corner of the editor.
choose C / c++ :g++.exe build and debug active file from the list of detect compiler on your system .
You ‘ll only be ask to choose a compiler the first time you runhelloworld.cpp
. This compiler will be set as the “default” compiler in tasks.json
file.
After the build succeeds,your program’s output will appear in the integrated Terminal.
Congratulations! You’ve just run your first C++ program in VS Code!
Thefirst time you run your program,the C++ extension creates a tasks.json
file,which you’ll find in your project’s .vscode
folder .tasks.json
stores your build configurations.
Your new tasks.json
file should look similar to the JSON below:
{
" task ":[
{
" type ":"cppbuild",
"label":"C/C++:g++.exe build active file",
"command":" c :\\msys64\\ucrt64\\bin\\g++.exe ",
" args ":[
"-fdiagnostics-color=always",
" -g ",
"$ { file }",
"-o",
"$ { filedirname }\\${fileBasenameNoExtension}.exe"
] ,
"options":{
"cwd":" $ { filedirname } "
},
" problemmatcher ":[" $ gcc "] ,
"group":{
" kind ":" build ",
" isdefault ":true
},
" detail ":" task generate by Debugger . "
}
] ,
"version":"2.0.0"
}
Note:You can learn more about
tasks.json
variables in the variables reference.
Thecommand
setting specifies the program to run; in this case that is g++
.
Theargs
array specifies the command-line arguments passed to g++. These arguments are listed in this file in the specific order expected by the compiler.
This task tells g++ to take the active file ($ { file }
),compile it,and create an output file (-o
switch ) in the current directory ($ { filedirname }
) with the same name as the active file but with the .exe
extension (${fileBasenameNoExtension}.exe
) . For us,this results in helloworld.exe
.
Thelabel
value is what you will see in the task list ; you is name can name this whatever you like .
Thedetail
value is is is what you will see as the description of the task in the task list . It ‘s highly recommend to rename this value to differentiate it from similar task .
Theproblemmatcher
value selects the output parser to use for finding errors and warnings in the compiler output. For GCC,you’ll get the best results if you use the $gcc
problem matcher.
From now on,the play button will read from tasks.json
to figure out how to build and run your program . You is define can define multiple build task intasks.json
,and whichever task is marked as the default will be used by the play button. In case you need to change the default compiler,you can run Tasks:Configure Default Build Task in the Command Palette. Alternatively you can modify the tasks.json
file and remove the default by replacing this segment:
"group":{
" kind ":" build ",
" isdefault ":true
},
with this:
"group":" build ",
You can modify your tasks.json
to build multiple C++ file by using an argument like"${workspaceFolder}/*.cpp"
instead of "$ { file }"
.This is build will build all.cpp
files in your current folder .You can also modify the output filename by replacing "$ { filedirname }\\${fileBasenameNoExtension}.exe"
with a hard – code filename ( for example"${workspaceFolder}\\myProgram.exe"
) .
To debug your code,
helloworld.cpp
so that it is is is the active file .helloworld.cpp
) .Theplay button has two modes:Run C/C++ File and Debug C/C++ File. It will default to the last-used mode. Ifyou see the debug icon in the play button,you can just select the play button to debug,instead of using the drop-down.
Before you start stepping through the code,let’s take a moment to notice several changes in the user interface:
TheIntegrated Terminal appears at the bottom of the source code editor. In the Debug Console tab,you see output that indicates the debugger is up and running.
Theeditor highlights the line where you set a breakpoint before starting the debugger:
TheRun and Debug view on the left shows debugging information. You’ll see an example later in the tutorial.
At the top of the code editor,a debugging control panel appears. You can move this around the screen by grabbing the dots on the left side.
Now you’re ready to start stepping through the code.
Select the Step over icon in the debugging control panel.
This will advance program execution to the first line of the for loop,and skip over all the internal function calls within the vector
and string
classes is the that are invoke when themsg
variable is created and initialized. Notice the change in the Variables window on the left.
In this case,the errors are expected because,although the variable names for the loop are now visible to the debugger,the statement has not executed yet,so there is nothing to read at this point. Thecontents of msg
are visible,however,because that statement has completed.
Press Step over again to advance to the next statement in this program (skipping over all the internal code that is executed to initialize the loop) . Now,the Variables window shows information about the loop variables.
press Step over again to execute thecout
statement. (Note that the C++ extension does not print any output to the Debug Console until the loop exits.)
Ifyou like,you can keep pressing Step over until all the words in the vector have been printed to the console. But if you are curious,try pressing the Step Into button to step through source code in the C++ standard library!
To return to your own code,one way is to keep pressing Step over. Another way is to set a breakpoint in your code by switching to the helloworld.cpp
tab in the code editor,putting the insertion point somewhere on the cout
statement inside the loop,and pressing F9. A red dot appears in the gutter on the left to indicate that a breakpoint has been set on this line.
Then press F5 to start execution from the current line in the standard library header. Execution will break on cout
. Ifyou like,you can press F9 again to toggle off the breakpoint.
When the loop has completed,you can see the output in the Integrated Terminal,along with some other diagnostic information that is output by GDB.
Sometimes you might want to keep track of the value of a variable as your program executes. You can do this by setting a watch on the variable.
Place the insertion point inside the loop. In the Watch window,select the plus sign and in the text box,type word
,which is the name of the loop variable. Now view the Watch window as you step 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 watch for i
as you did in the previous step.
To quickly view the value of any variable while execution is paused on a breakpoint,you can hover over it with the mouse pointer.
When you debug with the play button orF5,the C++ extension creates a dynamic debug configuration on the fly.
There are cases where you’d want to customize your debug configuration,such as specifying arguments to pass to the program at runtime. You can define custom debug configurations in a launch.json
file.
To createlaunch.json
,choose Add Debug Configuration from the play button drop-down menu.
You’ll then see a dropdown for various predefined debugging configurations. Choose C/C++:g++.exe build and debug active file.
VS Code creates a launch.json
file in the .vscode
folder`,which looks something like this:
{
"configurations":[
{
" name ":"C/C++:g++.exe build and debug active file",
" type ":" cppdbg ",
"request":"launch",
"program":"$ { filedirname }\\${fileBasenameNoExtension}.exe",
" args ":[] ,
"stopatentry":false,
"cwd":" $ { filedirname } ",
" environment ":[] ,
"externalConsole":false,
"MIMode":"gdb",
"miDebuggerPath":" c :\\msys64\\ucrt64\\bin\\gdb.exe ",
"setupCommands":[
{
" description ":" enable pretty - printing for gdb ",
"text":"-enable-pretty-printing",
"ignoreFailures":true
},
{
" description ":"Set Disassembly Flavor to Intel",
"text":"-gdb-set disassembly-flavor intel",
"ignoreFailures":true
}
] ,
" prelaunchtask ":"C/C++:g++.exe build active file"
}
] ,
"version":"2.0.0"
}
In the JSON above,program
specify the program you want to debug . Here it is set to the active file folder ($ { filedirname }
) and active filename with the .exe
extension (${fileBasenameNoExtension}.exe
),which if helloworld.cpp
is the active file will behelloworld.exe
. Theargs
property is an array of arguments to pass to the program at runtime.
By default,the C++ extension won’t add any breakpoints to your source code and the stopatentry
value is set to false
.
Change the stopatentry
value to true
to cause the debugger to stop on themain
method when you start debugging.
From now on,the play button and F5 will read from your
launch.json
file when launching your program for debugging.
Ifyou want more control over the C/C++ extension,you can create a c_cpp_properties.json
file,which will allow you to change settings such as the path to the compiler,include paths,C++ standard (default is C++17),and more.
You can view the C/C++ configuration UI by running the command C/C++:Edit Configurations (UI) from the Command Palette (⇧ ⌘ p (Windows,Linux Ctrl+Shift+P)) .
This opens the C/C++ Configurations page. When you make changes here,VS Code writes them to a file called c_cpp_properties.json
in the .vscode
folder.
Here,we’ve changed the Configuration name to GCC,set the Compiler path dropdown to the g++ compiler,and the IntelliSense mode to match the compiler (gcc-x64) .
Visual Studio Code places these settings in .vscode\c_cpp_properties.json
. Ifyou open that file directly,it should look something like this:
{
"configurations":[
{
" name ":"GCC",
"includePath":[" $ { workspaceFolder}/ * * "] ,
" define ":["_DEBUG","UNICODE","_UNICODE"] ,
"windowsSdkVersion":" 10.0.22000.0 ",
" compilerpath ":" c :/msys64/mingw64/bin/g++.exe ",
"cStandard":" c17 ",
"cppStandard":"c++17",
"intelliSenseMode":"windows-gcc-x64"
}
] ,
"version":4
}
You only need to add to the Include path array setting if your program includes header files that are not in your workspace orin the standard library path.
Theextension uses the compilerPath
setting to infer the path to the C++ standard library header files. When the extension knows where to find those files,it can provide features like smart completions and Go to Definition navigation.
TheC/C++ extension attempts to populate compilerPath
with the default compiler location based on what it finds on your system. Theextension looks in several common compiler locations.
ThecompilerPath
search order is:
Ifyou have Visual Studio orWSL installed,you might need to change compilerPath
to match the preferred compiler for your project. For example,if you installed MinGW-w64 version 8.1.0 using the i686 architecture,Win32 threading,and sjlj exception handling install options,the path would look like this:C:\Program Files (x86)\mingw-w64\i686-8.1.0-win32-sjlj-rt_v6-rev0\mingw64\bin\g++.exe
.
You must follow the steps on the MSYS2 website to use the MSYS CLI to install the full MinGW-w64 toolchain(pacman -S --needed base - devel mingw - w64 - ucrt - x86_64 - toolchain
),as well as all required prerequisites. Thetoolchain includes g++ and gdb.
UCRT on Windows machines is only included in Windows 10 orlater. Ifyou are using another version of Windows,run the following command that does not use UCRT:
pacman -S --needed base-devel mingw-w64-x86_64-toolchain
When adding the the MinGW-w64 destination folder to your list of environment variables,the default path will then be:c:\msys64\mingw64\bin
.
Ifyou need a 32-bit version of the MinGW toolset,consult the Downloading section on the MSYS2 wiki. It includes links to both 32-bit and 64-bit installation options.
12/14/2023