Using GCC with MinGWIn 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. Show
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. PrerequisitesTo successfully complete this tutorial, you must do the following steps:
Check your MinGW installationTo check that your Mingw-w64 tools are correctly installed and available, open a new Command Prompt and type: g++ --version gdb --versionIf you don't see the expected output or g++ or gdb is not a recognized command, make sure your PATH entry matches the Mingw-w64 binary location where the compilers are located. If the compilers do not exist at that PATH entry, make sure you followed the instructions on the MSYS2 website to install Mingw-w64. Create Hello WorldFrom 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: 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:
Add a source code fileIn the File Explorer title bar, select the New File button and name the file helloworld.cpp. Add hello world source codeNow 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 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.
Explore IntelliSenseIn 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. Run helloworld.cppRemember, the C++ extension uses the C++ compiler you have installed on your machine to build your program. Make sure you have a C++ compiler installed before attempting to run and debug helloworld.cpp in VS Code.
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.
The first time you run your program, the C++ extension creates tasks.json, which you'll find in your project's .vscode folder. tasks.json stores 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\\mingw64\\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" }
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. 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 as the description of the task in the tasks list. It's highly recommended to rename this value to differentiate it from similar tasks. 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. 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.jsonYou 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
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 click the play button to debug, instead of using the drop-down. Explore the debuggerBefore you start stepping through the code, let's take a moment to notice several changes in the user interface:
Step through the codeNow you're ready to start stepping through the code.
Set a watchSometimes 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.
Customize debugging with launch.jsonWhen 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, which looks something like this: { "version": "0.2.0", "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\\mingw64\\bin\\gdb.exe", "setupCommands": [ { "description": "Enable pretty-printing for gdb", "text": "-enable-pretty-printing", "ignoreFailures": true } ], "preLaunchTask": "C/C++: g++.exe build active file" } ] }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.
C/C++ configurationsIf 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.18362.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. Compiler pathThe 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:
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-w64\i686-8.1.0-win32-sjlj-rt_v6-rev0\mingw64\bin\g++.exe. TroubleshootingMSYS2 is installed, but g++ and gdb are still not foundYou must follow the steps on the MSYS2 website and use the MSYS CLI to install Mingw-w64, which contains those tools. MinGW 32-bitIf 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
5/13/2022 How do you fix G ++' is not recognized as an internal or external command operable program or batch file?After downloading, install MinGW and wait for the “MinGW Installation Manager” to show up.. When the “MinGW Installation Manager” shows up, click on mingw32-gcc-g++ then select “Mark for Installation”. In the menu at the top left corner, click on “Installation > Apply Changes”. Wait and allow to install completely.. How do I fix G + is not recognized as an internal?You need to set the environment PATH to include the directory of mingw's bin directory if you want o use gcc.exe or g++.exe in cmd . run 'path' or 'echo %PATH% in cmd.exe prompt.
How do I fix not recognized as an internal or external command?You can resolve this issue in three ways: First, use the full path of the executable file to launch the program. Second, add the program path to Windows environment variables. Finally, move the files to the System32 folder.
Why G ++ is not recognized Vscode?If you don't see the expected output or g++ or gdb is not a recognized command, make sure your PATH entry matches the Mingw-w64 binary location where the compilers are located. If the compilers do not exist at that PATH entry, make sure you followed the instructions on the MSYS2 website to install Mingw-w64.
|