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.
If you have any problems, feel free to file an issue for this tutorial in the VS Code documentation repository.
Prerequisites
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 latest version of MinGW-w64 via MSYS2, which provides up-to-date native builds of GCC, MinGW-w64, and other helpful C++ tools and libraries. This will provide you with the necessary tools to compile your code, debug it, and configure it to work with IntelliSense.
To install the MinGW-w64 toolchain, check out this video or follow the steps below:
-
You can download the latest installer from the MSYS2 page or use this direct link to the installer.
-
Run the installer and follow the steps of the installation wizard. Note that MSYS2 requires 64 bit Windows 8.1 or newer.
-
In the wizard, choose your desired Installation Folder. Record this directory for later. In most cases, the recommended directory is acceptable. The same applies when you get to setting the start menu shortcuts step. When complete, ensure the Run MSYS2 now box is checked and select Finish. This will open a MSYS2 terminal window for you.
-
In this terminal, install the MinGW-w64 toolchain by running the following command:
pacman -S --needed base-devel mingw-w64-ucrt-x86_64-toolchain
-
Accept the default number of packages in the
toolchain
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:- In the Windows search bar, type Settings to open your Windows Settings.
- Search for Edit environment variables for your account.
- In your User variables, select the
Path
variable and then select Edit. - Select New and add the MinGW-w64 destination folder you recorded during the installation process to the list. If you used the default settings above, then this will be the path:
C:\msys64\ucrt64\bin
. - Select OK, and then select OK again in the Environment Variables window to update the
PATH
environment variable.
You have to reopen any console windows for the updatedPATH
environment variable to be available.
Check your MinGW installation
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. If this is not the case:
- Make sure your PATH variable entry matches the MinGW-w64 binary location where the toolchain was installed. If the compilers do not exist at that PATH entry, make sure you followed the previous instructions.
- If
gcc
has the correct output but notgdb
, then you need to install the packages you are missing from the MinGW-w64 toolset.- If on compilation you are getting the «The value of miDebuggerPath is invalid.» message, one cause can be you are missing the
mingw-w64-gdb
package.
- If on compilation you are getting the «The value of miDebuggerPath is invalid.» message, one cause can be you are missing the
Create a Hello World app
First, lets get a project set up.
- Launch a Windows command prompt (Enter Windows command prompt in the Windows search bar).
- Run the following commands. These will create an empty folder called
projects
where you can place all your VS Code projects. There, the next commands will create and navigate to a subfolder calledhelloworld
. From there, you will openhelloworld
directly in VS Code.
mkdir projects
cd projects
mkdir helloworld
cd helloworld
code .
The «code .» command opens VS Code in the current working folder, which becomes your «workspace». Accept the Workspace Trust dialog by selecting Yes, I trust the authors since this is a folder you created.
As you go through the tutorial, you will see three files created in a .vscode
folder in the workspace:
tasks.json
(build instructions)launch.json
(debugger settings)c_cpp_properties.json
(compiler path and IntelliSense settings)
Add a Hello World source code file
In the File Explorer title bar, select the New File button and name the file helloworld.cpp
.
Add hello world source code
Now paste in this source code:
#include <iostream>
#include <vector>
#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 or open 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).
Explore IntelliSense
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 over vector
or string
to see their type information. If you 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. If you then add open parenthesis, IntelliSense will show information on which arguments are required.
If IntelliSense 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 found in the IntelliSense configuration documentation.
Run helloworld.cpp
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 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 detected compilers on your system.
You’ll only be asked to choose a compiler the first time you run helloworld.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!
Understanding tasks.json
The first 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:
{
"tasks": [
{
"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 generated by Debugger."
}
],
"version": "2.0.0"
}
Note: You can learn more about
tasks.json
variables in the variables reference.
The command
setting specifies the program to run; in this case that is g++
.
The args
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
.
The label
value is what you will see in the tasks list; you can name this whatever you like.
The detail
value is what you will see as the description of the task in the tasks list. It’s highly recommended to rename this value to differentiate it from similar tasks.
The problemMatcher
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 can define multiple build tasks in tasks.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",
Modifying tasks.json
Starting November 3, 2024, MSYS2 has disabled wildcard support for mingw-w64
by default. This change impacts how wildcards like "*.cpp"
are processed in build commands. To build multiple C++ files in your tasks.json
, you must explicitly list the files, use a build system like make
or cmake
or implement the following workarounds: https://www.msys2.org/docs/c/#expanding-wildcard-arguments.
If you previously used "${workspaceFolder}/*.cpp"
to compile all .cpp
files in the current folder, this will no longer work directly. Instead, you can manually list the files or define a build script.
Debug helloworld.cpp
To debug your code,
- Go back to
helloworld.cpp
so that it is the active file. - Set a breakpoint by clicking on the editor margin or using F9 on the current line.
- From the drop-down next to the play button, select Debug C/C++ File.
- Choose C/C++: g++ build and debug active file from the list of detected compilers on your system (you’ll only be asked to choose a compiler the first time you run or debug
helloworld.cpp
).
The play button has two modes: Run C/C++ File and Debug C/C++ File. It will default to the last-used mode. If you see the debug icon in the play button, you can just select the play button to debug, instead of using the drop-down.
Explore the debugger
Before you start stepping through the code, let’s take a moment to notice several changes in the user interface:
-
The Integrated 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.
-
The editor highlights the line where you set a breakpoint before starting the debugger:
-
The Run 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.
Step through the code
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
andstring
classes that are invoked 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. The contents 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 the
cout
statement. (Note that the C++ extension does not print any output to the Debug Console until the loop exits.) -
If you 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 thecout
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
. If you 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.
Set a watch
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 fori
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.
Customize debugging with launch.json
When you debug with the play button or F5, 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 create launch.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
specifies 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 be helloworld.exe
. The args
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 the main
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.
Adding additional C/C++ settings
If you 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
. If you open that file directly, it should look something like this:
{
"configurations": [
{
"name": "GCC",
"includePath": ["${workspaceFolder}/**"],
"defines": ["_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 or in the standard library path. It is strongly recommended not to add the system include path to the includePath
setting for compilers that we support.
Compiler path
The extension 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.
The C/C++ extension attempts to populate compilerPath
with a default compiler based on what it finds on your system. The extension looks in several common compiler locations but will only automatically select one that is in either one of the «Program Files» folders or whose path is listed in the PATH environment variable. If the Microsoft Visual C++ compiler can be found it will be selected, otherwise it will select a version of gcc, g++, or clang.
If you have more than one compiler installed, you might need to change compilerPath
to match the preferred compiler for your project. You may also use the C/C++: Select InteliSense Configuration… command in the Command Palette to select one of the compilers that the extension detected.
Troubleshooting
MSYS2 is installed, but g++ and gdb are still not found
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. The toolchain includes g++ and gdb.
As a Windows user, running the pacman command gives me an error
UCRT on Windows machines is only included in Windows 10 or later. If you 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
.
MinGW 32-bit
If you 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.
Next steps
- Explore the VS Code User Guide.
- Review the Overview of the C++ extension.
- Create a new workspace, copy your
.vscode
JSON files to it, adjust the necessary settings for the new workspace path, program name, etc. and start coding!
12/14/2023
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.
All in all, for ordinary people, mingw-w64 is suitable for learning C language, and vs2015 is better for real work. Of course, if you are working under Linux, code:: blocks may be an option, but the biggest possibility is that you must be accustomed to using gcc to compile programs. 4、 Download and install mingw-w64. Install MinGW-w64 Compiler. To install the compiler, use the Add-Ons menu. On the MATLAB Home tab, in the Environment section, click Add-Ons Get Add-Ons. Search for MinGW or select from Features. Building yprime.c Example. You can test the MinGW ® compiler. $ pacman -S mingw32/mingw-w64-i686-imagemagick $ pacman -S mingw32/mingw-w64-i686-python2-jinja Note on GPG keys While installing the above packages, pacman probably reported all sorts of warnings about gpg keys.
Install the TDM-GCC package into the directory c:mingw64, selecting to install all components. Select not to add MinGW-w64 to the PATH. After the installer completes, use the Start menu, right-click on ‘Computer’, select ‘Properties’ then ‘Advanced Systems Settings’ then ‘Advanced’ tab, click button ‘Environment variables’. And install using. Pacman -S packagenameofsomethingiwanttoinstall e.g. Pacman -S mingw-w64-x8664-gsl and from then on the GSL library is automatically found by your MinGW-w64 64-bit compiler! Open a MinGW-w64 shell: a) To build 32-bit things, open the ‘MinGW-w64 32-bit Shell’ b) To build 64-bit things, open the ‘MinGW-w64 64-bit Shell’.
After configuring VS Code, you will compile and debug a simple Hello World program in VS Code. 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.
If you have any problems, feel free to file an issue for this tutorial in the VS Code documentation repository.
Prerequisites
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)).
-
Install Mingw-w64 via the SourceForge website. Click Mingw-w64 to download the Windows Mingw-w64 installer.
- Run the installer.
- For Architecture select x86_64 and then select Next.
- Next again to use the default installation folder and install MinGW.
-
Add the path to your Mingw-w64
bin
folder to the WindowsPATH
environment variable by using the following steps:- In the Windows search bar, type ‘settings’ to open your Windows Settings.
- Search for Edit environment variables for your account.
- Choose the
Path
variable and then select Edit. - Select New and add the Mingw-w64 path to the system path. The exact path depends on which version of Mingw-w64 you have installed and where you installed it. If you used the settings above to install Mingw-w64, then add this to the path:
C:Program Filesmingw-w64x86_64-8.1.0-posix-seh-rt_v6-rev0mingw64bin
. - Select OK to save the updated PATH. You will need to reopen any console windows for the new PATH location to be available.
Check your MinGW installation
To check that your Mingw-w64 tools are correctly installed and available, open a new Command Prompt and type:
If you don’t see the expected output or g++
or gdb
is not a recognized command, check your installation (Windows Control Panel > Programs) and make sure your PATH entry matches the Mingw-w64 binary location where the compilers are located.
Create Hello World
From a Windows command prompt, create an empty folder called projects
where you can place all your VS Code projects. Then create a sub-folder called helloworld
, navigate into it, and open VS Code in that folder by entering the following commands:
The ‘code .’ command opens VS Code in the current working folder, which becomes your ‘workspace’. As you go through the tutorial, you will see three files created in a .vscode
folder in the workspace:
tasks.json
(build instructions)launch.json
(debugger settings)c_cpp_properties.json
(compiler path and IntelliSense settings)
Add a source code file
In the File Explorer title bar, select the New File button and name the file helloworld.cpp
.
Add hello world source code
Now paste in this source code:
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:
Install Mingw-w64compiler
You can also enable Auto Save to automatically save your file changes, by checking Auto Save in the main File menu.
The Activity Bar on the far left lets you open different views such as Search, Source Control, and Run. You’ll look at the Run view later in this tutorial. You can find out more about the other views in the VS Code User Interface documentation.
Note: When you save or open 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).
Explore IntelliSense
In your new helloworld.cpp
file, hover over vector
or string
to see type information. After the declaration of the msg
variable, start typing msg.
as you would when calling a member function. You should immediately see a completion list that shows all the member functions, and a window that shows the type information for the msg
object:
You can press the Tab key to insert the selected member; then, when you add the opening parenthesis, you will see information about any arguments that the function requires.
Build helloworld.cpp
Next, you’ll create a tasks.json
file to tell VS Code how to build (compile) the program. This task will invoke the g++ compiler to create an executable file based on the source code.
From the main menu, choose Terminal > Configure Default Build Task. In the dropdown, which will display a tasks dropdown listing various predefined build tasks for C++ compilers. Choose g++.exe build active file, which will build the file that is currently displayed (active) in the editor.
This will create a tasks.json
file in a .vscode
folder and open it in the editor.
Your new tasks.json
file should look similar to the JSON below:
The command
setting specifies the program to run; in this case that is g++. The args
array specifies the command-line arguments that will be passed to g++. These arguments must be specified in the order expected by the compiler. This task tells g++ to take the active file (${file}
), compile it, and create an executable file in the current directory (${fileDirname}
) with the same name as the active file but with the .exe
extension (${fileBasenameNoExtension}.exe
), resulting in helloworld.exe
for our example.
Note: You can learn more about task.json
variables in the variables reference.
The label
value is what you will see in the tasks list; you can name this whatever you like.
Mingw W64 Download Exe
The 'isDefault': true
value in the group
object specifies that this task will be run when you press ⇧⌘B (Windows, Linux Ctrl+Shift+B). This property is for convenience only; if you set it to false, you can still run it from the Terminal menu with Tasks: Run Build Task.
Running the build
-
Go back to
helloworld.cpp
. Your task builds the active file and you want to buildhelloworld.cpp
. -
To run the build task defined in
tasks.json
, press ⇧⌘B (Windows, Linux Ctrl+Shift+B) or from the Terminal main menu choose Run Build Task. -
When the task starts, you should see the Integrated Terminal panel appear below the source code editor. After the task completes, the terminal shows output from the compiler that indicates whether the build succeeded or failed. For a successful g++ build, the output looks something like this:
-
Create a new terminal using the + button and you’ll have a new terminal with the
helloworld
folder as the working directory. Rundir
and you should now see the executablehelloworld.exe
. -
You can run
helloworld
in the terminal by typinghelloworld.exe
(or.helloworld.exe
if you use a PowerShell terminal).
Note: You might need to press Enter a couple of times initially to see the PowerShell prompt in the terminal. This issue should be fixed in a future release of Windows.
Modifying tasks.json
You can modify your tasks.json
to build multiple C++ files by using an argument like '${workspaceFolder}*.cpp'
instead of ${file}
. This will build all .cpp
files in your current folder. You can also modify the output filename by replacing '${fileDirname}${fileBasenameNoExtension}.exe'
with a hard-coded filename (for example '${workspaceFolder}myProgram.exe'
).
Debug helloworld.cpp
Next, you’ll create a launch.json
file to configure VS Code to launch the GDB debugger when you press F5 to debug the program.
- From the main menu, choose Run > Add Configuration… and then choose C++ (GDB/LLDB).
- You’ll then see a dropdown for various predefined debugging configurations. Choose g++.exe build and debug active file.
VS Code creates a launch.json
file, opens it in the editor, and builds and runs ‘helloworld’.
The program
setting specifies 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 be helloworld.exe
.
Installing Mingw-w64 Architecture
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 the main
method when you start debugging.
Note: The preLaunchTask
setting is used to specify task to be executed before launch. Make sure it is consistent with the task.json
file label
setting.
Start a debugging session
- Go back to
helloworld.cpp
so that it is the active file. - Press F5 or from the main menu choose Run > Start Debugging. Before you start stepping through the source code, let’s take a moment to notice several changes in the user interface:
Installing Mingw-w64 Settings
Install Mingw-w64 Compiler
-
The Integrated Terminal appears at the bottom of the source code editor. In the Debug Output tab, you see output that indicates the debugger is up and running.
-
The editor highlights the first statement in the
main
method. This is a breakpoint that the C++ extension automatically sets for you: -
The Run 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.
Step through the code
Now you’re ready to start stepping through the code.
-
Click or press 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
andstring
classes that are invoked 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. The contents 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 the
cout
statement. (Note that as of the March 2019 release, the C++ extension does not print any output to the Debug Console until the loop exits.) -
If you 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 thecout
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
. If you 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.
Set a watch
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, click 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 fori
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.
C/C++ configurations
If you 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 .vscodec_cpp_properties.json
. If you open that file directly, it should look something like this:
You only need to add to the Include path array setting if your program includes header files that are not in your workspace or in the standard library path.
Compiler path
The extension 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.
The C/C++ extension attempts to populate compilerPath
with the default compiler location based on what it finds on your system. The extension looks in several common compiler locations.
The compilerPath
search order is:
- First check for the Microsoft Visual C++ compiler
- Then look for g++ on Windows Subsystem for Linux (WSL)
- Then g++ for Mingw-w64.
If you have Visual Studio or WSL installed, you may 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-w64i686-8.1.0-win32-sjlj-rt_v6-rev0
.
Installing Mingw W64 On Windows
Next steps
- Explore the VS Code User Guide.
- Review the Overview of the C++ extension.
- Create a new workspace, copy your
.vscode
JSON files to it, adjust the necessary settings for the new workspace path, program name, and so on, and start coding!
MinGW (Minimalist GNU for Windows) is a free and open-source software development environment that allows users to create native Windows applications. It includes a collection of programming tools, compilers, and libraries, including GCC (GNU Compiler Collection) for C and C++. One of the critical steps when working with MinGW is ensuring that the MinGW installation directory is added to your system’s PATH. This allows you to compile and run your code directly from the Command Prompt or terminal without needing to navigate to the MinGW directory each time.
This detailed guide will walk you through the process of adding MinGW to the PATH variable in Windows 11. By the end, you’ll have everything you need to start coding in C or C++ using MinGW.
Step 1: Download and Install MinGW
Before you can add MinGW to your system PATH, you need to download and install it. Follow these steps:
-
Download MinGW:
- Open your web browser and navigate to the MinGW-w64 website.
- You may also visit the SourceForge page for MinGW-w64.
- Choose the appropriate version for your system (32-bit or 64-bit) and download the installer.
-
Install MinGW:
- Locate the downloaded installer and double-click it to run.
- Follow the prompts in the setup wizard. When asked to select the installation directory, you can stick with the default or choose your desired directory (e.g.,
C:MinGW
). - Make sure to include the
GCC
component in your installation options.
-
Complete the Installation:
- Continue through the installation process until MinGW is installed. You can close the installer once it completes.
Step 2: Locate Your MinGW Installation Directory
Once MinGW is installed, you need to determine the exact directory location for the bin folder that contains MinGW executables. Typically, this folder is located at:
- For the default installation path:
C:MinGWbin
If you customized your installation path during the setup, locate that directory instead.
Step 3: Add MinGW to System PATH
Now that you know where your MinGW installation is, it’s time to add it to your system PATH. Follow these steps to do this:
-
Open Settings:
- Click the Start menu or press the Windows key on your keyboard.
- Type in “Settings” and hit Enter.
-
Navigate to System Settings:
- In the Settings window, click on the System tab on the left sidebar.
- Scroll down and select About.
-
Access Advanced System Settings:
- On the right side of the About page, click on Advanced system settings.
-
Open Environment Variables:
- In the System Properties window, click on the Environment Variables button located at the bottom right corner.
-
Locate the Path Variable:
- In the Environment Variables window, you will see two sections — User variables and System variables.
- To make MinGW available to your user only, select the Path variable under the User variables section, then click on Edit. If you want to add it for all users, do the same under the System variables section.
-
Add MinGW Path:
- In the Edit Environment Variable window, click on New.
- Type or paste the path to the MinGW
bin
folder (e.g.,C:MinGWbin
) into the new entry. - Click OK to close the Edit Environment Variable window.
- Click OK again to close the Environment Variables window, and finally, click OK in the System Properties window.
Step 4: Verify Your Installation
To ensure that MinGW has been successfully added to your PATH, follow these steps to verify:
-
Open Command Prompt:
- Press the Windows key + R to open the Run dialog.
- Type
cmd
and hit Enter to open the Command Prompt.
-
Check GCC Version:
- In the Command Prompt window, type the following command:
gcc --version
- If MinGW has been successfully added to your PATH, you should see output displaying the version of GCC that is installed.
- In the Command Prompt window, type the following command:
If you see an error message indicating that the command is not recognized, double-check the steps above to ensure you’ve entered the correct path.
Step 5: Compile and Run Your First Program
Now that you have MinGW set up and verified, let’s write a simple C program and compile it using MinGW.
-
Create a Simple C Program:
-
Open a text editor (like Notepad) and enter the following sample C program:
#include int main() { printf("Hello, World!n"); return 0; }
- Save the file with a
.c
extension, for example,hello.c
, in a directory of your choice (e.g.,C:UsersYourUsernameDocuments
).
-
-
Compile the C Program:
- Go back to the Command Prompt.
- Navigate to the directory where you saved your C file. Use the
cd
(change directory) command for this. For example:cd C:UsersYourUsernameDocuments
- Now compile the program using the
gcc
command:gcc hello.c -o hello
- This command tells GCC to compile
hello.c
and output an executable namedhello.exe
.
-
Run the Program:
- After compiling the program, run the executable by typing:
./hello
- You should see the output:
Hello, World!
- After compiling the program, run the executable by typing:
Congratulations! You have successfully added MinGW to your system’s PATH, compiled a C program, and executed it.
Troubleshooting Common Issues
Here are some common problems you may encounter, along with their solutions:
1. GCC not recognized
If you receive an error that the gcc
command is not recognized, double-check the following:
- Ensure MinGW is correctly installed.
- Verify that the path you added to the system’s PATH variable points directly to the
bin
folder of your MinGW installation and is correctly configured.
2. Permissions Issues
If you encounter permission-related errors, it may be necessary to run Command Prompt in Administrator mode. Right-click on the Command Prompt shortcut and select Run as administrator.
3. Correcting Errors
If you experience issues while compiling code, take care to read the error messages that GCC returns. Typical errors include syntax errors, missing semicolons, and mismatched braces. The terminal will usually point you to the line of code where the error occurred, making it easier to troubleshoot.
Additional Resources
Learning C or C++
To further enhance your skills in C or C++, consider exploring online resources, books, or courses. Here are some suggestions:
-
Online Platforms:
- Codecademy
- Coursera
- edX
-
Books:
- «The C Programming Language» by Brian W. Kernighan and Dennis M. Ritchie
- «C++ Primer» by Stanley B. Lippman, Josée Lajoie, and Barbara E. Moo
Community Support
Participating in programming communities can also boost your learning. Websites such as Stack Overflow and forums dedicated to C/C++ programming can provide assistance and insights from experienced developers.
Conclusion
In this guide, we explored how to download and install MinGW, add it to the PATH variable in Windows 11, verify the installation, and compile and run a simple C program. Keeping your development setup straightforward and efficient is crucial, and adding MinGW to your PATH is a vital step in ensuring ease of access to your development tools.
By following this guide, you can quickly start developing applications using MinGW on Windows 11. Whether you’re a beginner or an experienced programmer, having the right setup is key to successful software development. Happy coding!
MinGW-w64 — набор средств разработки для Windows, включает в себя компилятор GNU C/C++, отладчик gdb, профайлер gprof, системы сборки make и cmake и прочие утилиты комплекта GNU. MinGW расшифровывается, как Minimalistic Gnu for Windows. Проект отделился от проекта MinGW.
Сайт проекта: https://www.mingw-w64.org/
Установка mingw-w64
Существуют различные независимые сборки mingw-w64, большинство их которых распространяется в виде нескольких архивов, которые необходимо отдельно распаковывать. Разобраться в том, какие именно архивы нужно скачивать и распаковывать довольно сложно. Вариант установки с использованием exe-приложения, самостоятельно скачивающего нужные пакеты, к сожалению, содержит весьма устаревшую версию 8.1.0 компилятора.
Довольно простой способ установки (понадобится скачать только один архив) актуальной версии компилятора — это использование сайта winlibs.com.
Откройте этот сайт и перейдите к разделу «Download». Там будет довольно много разных ссылок на скачивание, расскажем как выбрать правильный архив, если вы не знаете в точности, что именно вам нужно.
Перейдите к разделу «Release versions» — «UCRT runtime». Выберите самую верхнюю версию MinGW в списке, она помечена, как LATEST. Вам нужна сборка с POSIX threads, версия для Win64. Если предлагаются варианты сборки с LLVM/Clang/LLD/LLDB, выберите вариант без (without) LLVM/Clang/LLD/LLDB (по крайней мере, если вы не знаете точно, что вам нужны именно LLVM/Clang/LLD/LLDB). Выберите zip-архив (если у вас установлен архиватор 7-zip, то можете скачать архив 7-zip, он меньше). То есть вам понадобится вот этот файл.
Выбор архива для скачивания mingw-w64 c winlibs.com
Прямая ссылка на скачивание архива с компилятором gcc 12.2.0 (последняя версия на февраль 2023): https://github.com/brechtsanders/winlibs_mingw/releases/download/14.2.0posix-19.1.1-12.0.0-ucrt-r2/winlibs-x86_64-posix-seh-gcc-14.2.0-mingw-w64ucrt-12.0.0-r2.zip
Внутри скачанного архива будет каталог mingw64. Распакуйте этот каталог на диск, лучше всего не использовать каталоги с пробелами или русскими буквами в именах (в том числе «Program Files»), поэтому лучше всего распаковать архив прямо в корень диска C:\. Далее будем считать, что у вас получился каталог C:\mingw64, внутри которого есть подкаталоги bin, include, lib, libexec, share и x86_64-w64-mingw32.
Добавление mingw-w64 в PATH
Для того, чтобы можно было использовать приложения из распакованного архива, а сторонние среды разработки, такие как Code::Blocks или Visual Studio Code могли найти компилятор, необходимо подкаталог bin из распакованного архива добавить в системную переменную Path.
Вам необходимо открыть окно «Свойства системы» панели управления Windows. Для этого нужно открыть проводник, сделать правый клик мышью на «Этот компьютер», выбрать «Свойства». Появится окно «Система — О системе», в котором нужно кликнуть на «Дополнительные параметры системы».
Или можно сразу открыть окно «Свойства системы», если нажать на Win+R, в строку «Открыть» ввести команду sysdm.cpl, затем нажать Enter.
В окне «Свойства системы» выберите вкладку «Дополнительно» и нажмите на «Переменные среды…». Верхний список — это переменные среды для текущего пользователя, нижний список — системные переменные. В списке системных переменных выберите Path и нажмите на кнопку «Изменить»… Нажмите на кнопку «Создать», в списке появится новая строка. Нажмите на кнопку «Обзор» и выберите каталог C:\mingw64\bin (или подкаталог bin подкаталога mingw64, если вы распаковали его в другое место). Нажмите на OK, затем на OK, затем на OK.
Подробней про переменные среды и их изменение можно прочитать здесь.
Проверка работы компилятора
После распаковки архива и добавления MinGW-w64 в Path, запустите командную строку. Нажмите на Win+R и введите команду cmd, затем нажмите Enter.
Наберите команду g++. Вы должны увидеть сообщение «g++: fatal error: no input files compilation terminated». Наберите команду
g++ --version
Вы увидите сообщение с версией компилятора. Убедитесь, что версия соответствует той, которую вы скачали.
Пример вывода g++ из командной строки для проверки работы и версии компилятора