Introduction to C++ and Mingw-w64 in Visual Studio Code (2023)

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:

  1. installvisual studio code.

  2. 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)).

    Introduction to C++ and Mingw-w64 in Visual Studio Code (1)

  3. 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.

  4. follow thatInstallationinstructions on theMSYS2 Locationto install Mingw-w64. Be sure to run any necessary start menus andpac-manDomain.

  5. Install the mingw-w64 toolchain (pacman -S --necesita base-devel mingw-w64-x86_64-toolchain). run orpac-mancommand in an MSYS2 terminal. Accept the default to install all membersToolboxGroup.

  6. Add the path to your mingw-w64containerget for windowsFARenvironment variable with the following steps:

    1. Type "settings" in the Windows search bar to open Windows settings.
    2. Look forEdit environment variables for your account.
    3. Select theFarvariable in youruser variablesand then selectTo edit.
    4. 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.
    5. 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
  1. If you don't see the expected result org ++ogdbis 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.
  2. SeCCGhas the correct output, but nogdb, then you need to install the missing packages in the mingw-w64 toolset.
    • missing themingw-w64-gdbThe packet is one of the causes of "The value of myDebuggerPath is invalid". Message when trying to compile if your PATH is correct.

create hello world

At a Windows command prompt, create an empty folder namedProjectswhere 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.vscodeFolders 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.

Introduction to C++ and Mingw-w64 in Visual Studio Code (2)

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:

Introduction to C++ and Mingw-w64 in Visual Studio Code (3)

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 thatX(clear notification).

Discover IntelliSense

in your newhallowelt.cppfile, hover over itVectororopeto view type information. After the explanation ofNewsVariable, 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 forNewsObject:

Introduction to C++ and Mingw-w64 in Visual Studio Code (4)

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.cppnot VS code.

  1. Openhallowelt.cppto make it the active file.

  2. Hit the play button in the top right corner of the editor.

    Introduction to C++ and Mingw-w64 in Visual Studio Code (5)

  3. ChooseC/C++: g++.exe builds and debugs the active filefrom the list of compilers detected on your system.

    Introduction to C++ and Mingw-w64 in Visual Studio Code (6)

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.jsonArchive.

  1. After a successful compilation, the output of your program appears in the insertTerminal.

    Introduction to C++ and Mingw-w64 in Visual Studio Code (7)

When you run your program for the first time, the C++ extension createsTasks.jsonWhat will you find in your project?.vscodePasta.Tasks.jsonsave the build configuration.

your newTasks.jsonThe 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 itTasks.jsonVariablesvariable reference.

odomainthe configuration specifies the program to run; in this case it is g++.argumentarray 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.exerenovation (${fileBasenameNoExtension}.exe), resultingholamundo.exefor our example.

olabelthe value is what you see in the task list; you can name it whatever you want.

oDetailThe 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.jsonto 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.jsonArchive 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.jsonto create multiple C++ files with one argument like"${workspace folder}/*.cpp"rather${file}.which will build everything.cppfiles 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

  1. times forhallowelt.cppto make it the active file.
  2. Set a breakpoint by clicking on the editor border or by using F9 on the current line.Introduction to C++ and Mingw-w64 in Visual Studio Code (8)
  3. Select from the dropdown menu next to the play buttonDebugging C/C++ files.Introduction to C++ and Mingw-w64 in Visual Studio Code (9)Introduction to C++ and Mingw-w64 in Visual Studio Code (10)
  4. 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).Introduction to C++ and Mingw-w64 in Visual Studio Code (11)

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.

Introduction to C++ and Mingw-w64 in Visual Studio Code (12)

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:

    Introduction to C++ and Mingw-w64 in Visual Studio Code (13)

  • 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.

    Introduction to C++ and Mingw-w64 in Visual Studio Code (14)

step through code

Now you can start stepping through the code.

  1. Click or press the buttonget over itIcon in the Debugging Control Panel.

    Introduction to C++ and Mingw-w64 in Visual Studio Code (15)

    This moves program execution to the first line of the for loop and skips any internal function calls inside the for loop.VectormiropeClasses that are called when theNewsVariable created and initialized. Notice the change inVariablesleft window.

    Introduction to C++ and Mingw-w64 in Visual Studio Code (16)

    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. contentNewsthey are visible, however, since this statement is complete.

  2. 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.

  3. Pressget over itrun againcoutExplanation. (Note that as of the March 2019 release, the C++ extension is not shipped to theconsole debugginguntil the loop ends.)

  4. 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!

    Introduction to C++ and Mingw-w64 in Visual Studio Code (17)

    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 changehallowelt.cppGuide in the code editor, place the insertion point somewhere in thecoutinstruction inside the loop and pressF9. A red dot appears in the left margin to indicate that a breakpoint has been set on that line.

    Introduction to C++ and Mingw-w64 in Visual Studio Code (18)

    then pressF5to start execution from the current line in the standard library header. execution is stoppedcout. 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.

    Introduction to C++ and Mingw-w64 in Visual Studio Code (19)

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.

  1. Place the insertion point inside the loop. In itTo participateIn the window, click the plus sign and type in the text boxmust, which is the name of the loop variable. Now watch the clock window as you go through the loop.

    Introduction to C++ and Mingw-w64 in Visual Studio Code (20)

  2. Add another watch by adding this statement before the loop:int i = 0;. Then inside the loop add this statement:++I;. now add a clockUEas in the previous step.

  3. To quickly see the value of any variable while execution is paused at a breakpoint, you can hover over it.

    Introduction to C++ and Mingw-w64 in Visual Studio Code (21)

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.jsonArchive.

Createlaunch.json, chooseAdd debug configurationin the play button dropdown menu.

Introduction to C++ and Mingw-w64 in Visual Studio Code (22)

You will see a dropdown menu for several predefined debugging configurations. ChooseC/C++: g++.exe builds and debugs the active file.

Introduction to C++ and Mingw-w64 in Visual Studio Code (23)

VS Code creates alaunch.jsonfile 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,programspecifies 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.exerenovation (${fileBasenameNoExtension}.exe), Hehallowelt.cppis the active fileholamundo.exe. oargumentThe 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 entranceThe value is defined asINCORRECT.

change thatstop at the entrancevalue forTRUEto make the debugger stopPrincipalmethod when you start debugging.

From now on the play button andF5i will read about youlaunch.jsonfile 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.jsonfile 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)).

Introduction to C++ and Mingw-w64 in Visual Studio Code (24)

This opens theC/C++ Configurationbook page. If you make changes here, VS Code writes them to a file calledc_cpp_properties.jsonNO.vscodePasta.

Here we change themconfiguration nameforCCG, Put thatcompiler pathDropdown menu for g++ and compilersIntelliSense modematching the compiler (gcc-x64).

Introduction to C++ and Mingw-w64 in Visual Studio Code (25)

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 thecompiladorPathto 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 fillcompiladorPathwith the default compiler location based on what it finds on your system. The extension looks in several common compiler locations.

ocompiladorPathThe 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 changescompiladorPathmatching 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 thatgdbWashing 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.vscodeJSON, adjust the necessary settings for the new workspace path, program name, etc. and start coding!

13.05.2022

Top Articles
Latest Posts
Article information

Author: Annamae Dooley

Last Updated: 03/15/2023

Views: 6614

Rating: 4.4 / 5 (45 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Annamae Dooley

Birthday: 2001-07-26

Address: 9687 Tambra Meadow, Bradleyhaven, TN 53219

Phone: +9316045904039

Job: Future Coordinator

Hobby: Archery, Couponing, Poi, Kite flying, Knitting, Rappelling, Baseball

Introduction: My name is Annamae Dooley, I am a witty, quaint, lovely, clever, rich, sparkling, powerful person who loves writing and wants to share my knowledge and understanding with you.