Как добавить mingw в path windows 10

Configuring the C++ extension in Visual Studio Code to target g++ and gdb on a Mingw-w64 installation

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 programs that run on Windows.

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:

  1. Install Visual Studio Code.

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

    C/C++ extension

  3. 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. You can download the latest installer from the MSYS2 page or use this link to the installer.

  4. Follow the Installation instructions on the MSYS2 website to install Mingw-w64. Take care to run each required Start menu and pacman command.

  5. Install the Mingw-w64 toolchain (pacman -S --needed base-devel mingw-w64-x86_64-toolchain). Run the pacman command in a MSYS2 terminal. Accept the default to install all the members in the toolchain group.

  6. Add the path to your Mingw-w64 bin folder to the Windows PATH environment variable by using the following steps:

    1. In the Windows search bar, type ‘settings’ to open your Windows Settings.
    2. Search for Edit environment variables for your account.
    3. Choose the Path variable in your User variables and then select Edit.
    4. Select New and add the Mingw-w64 destination folder 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:msys64mingw64bin.
    5. 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:

gcc --version
g++ --version
gdb --version
  1. 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.
  2. If gcc has the correct output but not gdb, then you need to install the packages you are missing from the Mingw-w64 toolset.
    • Missing the mingw-w64-gdb package is one cause of the «The value of miDebuggerPath is invalid.» message upon attempted compilation if your PATH is correct.

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:

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 source code file

In the File Explorer title bar, select the New File button and name the file helloworld.cpp.

New File title bar button

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:

File Explorer

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:

Statement completion IntelliSense

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

Remember, 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.

  1. Open helloworld.cpp so that it is the active file.

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

    Screenshot of helloworld.cpp and play button

  3. Choose C/C++: g++.exe build and debug active file from the list of detected compilers on your system.

    C++ debug configuration dropdown

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.

  1. After the build succeeds, your program’s output will appear in the integrated Terminal.

    screenshot of program output

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"
}

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

  1. Go back to helloworld.cpp so that it is the active file.
  2. Set a breakpoint by clicking on the editor margin or using F9 on the current line.
    screenshot of breakpoint in helloworld.cpp
  3. From the drop-down next to the play button, select Debug C/C++ File.
    Screenshot of play button drop-down
    Screenshot of play button drop-down
  4. 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/debug helloworld.cpp).
    C++ debug configuration dropdown

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.

screenshot of play button in debug mode

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 Output 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:

    Initial breakpoint

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

    Debugging controls

Step through the code

Now you’re ready to start stepping through the code.

  1. Click or press the Step over icon in the debugging control panel.

    Step over button

    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 that are invoked when the msg variable is created and initialized. Notice the change in the Variables window on the left.

    Debugging windows

    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.

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

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

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

    Breakpoint in gcc standard library header

    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.

    Breakpoint in main

    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.

    Debug output in terminal

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.

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

    Watch window

  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 watch for i as you did in the previous step.

  3. To quickly view the value of any variable while execution is paused on a breakpoint, you can hover over it with the mouse pointer.

    Mouse hover

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.

Add debug configuration play button menu

You’ll then see a dropdown for various predefined debugging configurations. Choose C/C++: g++.exe build and debug active file.

C++ debug configuration dropdown

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.

From now on, the play button and F5 will read from your launch.json file when launching your program for debugging.

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

Command Palette

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

Command Palette

Visual Studio Code places these settings in .vscodec_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 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-rev0mingw64bing++.exe.

Troubleshooting

MSYS2 is installed, but g++ and gdb are still not found

You must follow the steps on the MSYS2 website and use the MSYS CLI to install Mingw-w64, which contains those tools. You will also need to install the full Mingw-w64 toolchain (pacman -S --needed base-devel mingw-w64-x86_64-toolchain) to get the gdb debugger.

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, and so on, and start coding!

5/13/2022

Order Area TOCTitle ContentId PageTitle DateApproved MetaDescription

3

cpp

GCC on Windows

7efec972-6556-4526-8aa8-c73b3319d612

Get Started with C++ and Mingw-w64 in Visual Studio Code

5/13/2022

Configuring the C++ extension in Visual Studio Code to target g++ and gdb on a Mingw-w64 installation

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 programs that run on Windows.

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:

  1. Install Visual Studio Code.

  2. Install the C/C++ extension for VS Code. You can install the C/C++ extension by searching for ‘c++’ in the Extensions view (kb(workbench.view.extensions)).

    C/C++ extension

  3. 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. You can download the latest installer from the MSYS2 page or use this link to the installer.

  4. Follow the Installation instructions on the MSYS2 website to install Mingw-w64. Take care to run each required Start menu and pacman command.

  5. Install the Mingw-w64 toolchain (pacman -S --needed base-devel mingw-w64-x86_64-toolchain). Run the pacman command in a MSYS2 terminal. Accept the default to install all the members in the toolchain group.

  6. Add the path to your Mingw-w64 bin folder to the Windows PATH environment variable by using the following steps:

    1. In the Windows search bar, type ‘settings’ to open your Windows Settings.
    2. Search for Edit environment variables for your account.
    3. Choose the Path variable in your User variables and then select Edit.
    4. Select New and add the Mingw-w64 destination folder 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:msys64mingw64bin.
    5. 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:

gcc --version
g++ --version
gdb --version
  1. 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.
  2. If gcc has the correct output but not gdb, then you need to install the packages you are missing from the Mingw-w64 toolset.
    • Missing the mingw-w64-gdb package is one cause of the «The value of miDebuggerPath is invalid.» message upon attempted compilation if your PATH is correct.

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:

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 source code file

In the File Explorer title bar, select the New File button and name the file helloworld.cpp.

New File title bar button

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 kb(workbench.action.files.save) to save the file. Notice how the file you just added appears in the File Explorer view (kb(workbench.view.explorer)) in the side bar of VS Code:

File Explorer

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:

Statement completion IntelliSense

You can press the kbstyle(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.cpp

Remember, 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.

  1. Open helloworld.cpp so that it is the active file.

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

    Screenshot of helloworld.cpp and play button

  3. Choose C/C++: g++.exe build and debug active file from the list of detected compilers on your system.

    C++ debug configuration dropdown

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.

  1. After the build succeeds, your program’s output will appear in the integrated Terminal.

    screenshot of program output

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"
}

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 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:

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

  1. Go back to helloworld.cpp so that it is the active file.
  2. Set a breakpoint by clicking on the editor margin or using F9 on the current line.
    screenshot of breakpoint in helloworld.cpp
  3. From the drop-down next to the play button, select Debug C/C++ File.
    Screenshot of play button drop-down
    Screenshot of play button drop-down
  4. 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/debug helloworld.cpp).
    C++ debug configuration dropdown

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.

screenshot of play button in debug mode

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 Output 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:

    Initial breakpoint

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

    Debugging controls

Step through the code

Now you’re ready to start stepping through the code.

  1. Click or press the Step over icon in the debugging control panel.

    Step over button

    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 that are invoked when the msg variable is created and initialized. Notice the change in the Variables window on the left.

    Debugging windows

    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.

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

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

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

    Breakpoint in gcc standard library header

    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 kb(editor.debug.action.toggleBreakpoint). A red dot appears in the gutter on the left to indicate that a breakpoint has been set on this line.

    Breakpoint in main

    Then press kb(workbench.action.debug.start) to start execution from the current line in the standard library header. Execution will break on cout. If you like, you can press kb(editor.debug.action.toggleBreakpoint) 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.

    Debug output in terminal

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.

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

    Watch window

  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 watch for i as you did in the previous step.

  3. To quickly view the value of any variable while execution is paused on a breakpoint, you can hover over it with the mouse pointer.

    Mouse hover

Customize debugging with launch.json

When you debug with the play button or kb(workbench.action.debug.start), 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.

Add debug configuration play button menu

You’ll then see a dropdown for various predefined debugging configurations. Choose C/C++: g++.exe build and debug active file.

C++ debug configuration dropdown

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.

From now on, the play button and kb(workbench.action.debug.start) will read from your launch.json file when launching your program for debugging.

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 (kb(workbench.action.showCommands)).

Command Palette

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

Command Palette

Visual Studio Code places these settings in .vscodec_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 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-rev0mingw64bing++.exe.

Troubleshooting

MSYS2 is installed, but g++ and gdb are still not found

You must follow the steps on the MSYS2 website and use the MSYS CLI to install Mingw-w64, which contains those tools. You will also need to install the full Mingw-w64 toolchain (pacman -S --needed base-devel mingw-w64-x86_64-toolchain) to get the gdb debugger.

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, and so on, and start coding!

Данный текст будет полезен тем, кто давно хотел слезть с иглы тяжеленных IDE, но настройка компилятора под себя – казалось делом неблагодарным и запутанным.

VS Code – это лишь редактор кода. Это не среда разработки – здесь нет встроенного компилятора или дебаггера. Здесь есть только их поддержка. Чем более инструмент универсален – тем сложнее вначале разобраться в его особенностях. Однако, здесь нет ничего невозможного! Если правильно один раз настроить VS Code, то вы получите замечательную среду с помощью которой можно поддерживать различные проекты на совершенно разных языках.

VS Code является легковесным, кроссплатформенным редактором кода. Одной из его главных особенностей является поддержка кучи плагинов. Плагины позволяют расширять технологию IntelliSense (автодополнение кода) на разные языки программирования, добавлять поддержку специфического оборудования, отладчиков и прочее. Очень приятная и гибкая цветовая схема не раздражает даже после многочасового просиживания в процессе работы.

В общем-то поэтому решил написать как подготовить себе приятную среду разработки. В данном случае – под C и C++

Картинки кликабельны. И их максимально много. Если считаете, что что-то слишком очевидно, то пропустите этот момент

Чаще всего используется компилятор gcc. Данный компилятор обычно идет совместно с Unix-осью. Для того, чтобы работать с этим компилятором на Windows, нужно установить некоторые инструменты разработки. Есть два больших и известных проекта, созданных с данной целью:

  • MinGW
  • Cygwin

Главное их отличие в том, что MinGW сосредоточен в основном на компиляторе с некой поддержкой системных команд, в то время как Cygwin старается эмулировать полноценную UNIX-среду.

Обсуждение на Stack Overflow на эту тему

https://stackoverflow.com/questions/771756/what-is-the-difference-between-cygwin-and-mingw

Установка MinGW

Первым делом нужно убедится, что на компьютере уже не установлен компилятор gcc. Нажмем Win+R и вызовем командную строку.

C:UsersUser> gcc -version

Если компилятор не установлен – выведется сообщение, что программа не найдена. Иначе, можно опустить установку и настройку MinGW и переходить прямо к разделу с настройкой VS Code.

Закрываем консоль (“cmd“) и переходим на официальный сайт проекта MinGW http://www.mingw.org/.

Ищем ссылку “Download” и переходим. Должно открыться что-то подобное, как на рисунке снизу.

Выбираем необходимые нам пакеты. Нам нужен базовый пакет mingw32-base и mingw32-gcc-g++. Отмечаем их

Внимание – приписка 32 в названии не означает работу приложения только и/или нацеленно на 32-битной платформе

После чего применяем внесенные изменения

Видим, что будет установлено/обновлено 24 пакета

Новое окно сообщает об успешном применении изменений

Теперь можем перейти в папку установки и убедиться в том, что все необходимое установлено (g++.exe и gcc.exe)

Выполним проверку установки переменной PATH. Проведем такую же проверку, как и в начале. Нажмем Win+R и вызовем командную строку.

Попросим компилятор вывести его версию следующей командой:

C:UsersUser> gcc -version

Если все сработало как нужно, то переходим к разделу с настройкой VS Code.

Если в консоли появилась ошибка, то нужно настроить переменную PATH. Это глобальная системная переменная и содержит в себе каталог исполняемых программ. То есть её настройка позволяет запустить программу по имени, не указывая полный путь до исполняемого файла. Их есть два вида – отдельная для каждого пользователя и одна общесистемная, которая доступна каждому пользователю.

Как настроить переменную PATH

Переходим в “Этот компьютер” и нажимаем правую кнопку -> свойства.

Далее в левой колонке жмем “Дополнительные параметры среды

Далее в “Переменные среды

Выбираем в списке переменных сред для пользователя выбираем переменную PATH и жмем “Изменить“.

Жмем “Создать” и вписываем полный путь до папки MinGWbin

Нажимаем “Ок” и снова вызываем командную строку – Win+Rcmd.

Внимание – чтобы изменения переменной PATH вступили в силу, командную строку нужно перезапустить, если она осталась открытой.

Выводим для проверки версию компилятора:

C:UsersUser> gcc -version

Заодно проверим дебаггер:

C:UsersUser> gdb -version

VS Code – Hellow World

Скачиваем с официального сайта абсолютно бесплатный VS Code.

https://code.visualstudio.com/

Процесс установки опустим – подсказок установщика достаточно

Для корректного автодополнения, дебага и подсказок по документации стоит установить расширение C/C++.

Расширения устанавливаются прямо из VS Code во вкладке “Extensions” или Ctrl+Shift+X. На нижней картинке эта вкладка подчеркнута в левом столбце.

Найдем через строку поиска C/C++ и установим.

Далее создаем папку будущего проекта в произвольном месте на компьютере. Свою назвал “helloworld“. Она будет папкой всего проекта, который вы будете разрабатывать. В VS Code открываем папку используя File > Open Folder…

Откроется проект. Пока он пустой. Создадим первый файл в проекте через File > New File

Чтобы VS Code начал предлагать подсказки по вводу и подсвечивать синтаксис, следует сразу после создания файла сохранить его в необходимом расширении. По сути сейчас вы определяете язык будущего проекта. Нажимаете File > Save… и в открывшемся окне выбираете тип файла. Т.к. наш тестовый проект пишется на Си, выбираем его в выпадающем списке Тип файла.

Теперь при вводе текста будут появляться подсказки с автодополнением. Для подстановки предложенного автодополнения можно нажать Tab. В VS Code достаточно много удобных хоткеев. Посмотреть все быстрые клавиши можно тут File > Preferences > Keyboard Shortcuts

Запишем наш код HelloWorld в файл. В принципе, можно писать любой код – главное, чтобы был вывод в консоль для отладки.

#include <stdio.h>

int main(void)
{
    char * msg = "Hello World";
    printf("%s", msg);
    return 0;
}

Настройка компилятора

Время перейти к настройке компилятора и дебаггера.

Компилятор позволит из написанного кода собрать рабочее приложение.

Переходим Terminal > Configure Default Build Task…

Мы изначально определили язык программирования (во время сохранения) и VS Code самостоятельно нашел компилятор – нам предложено задать сценарий работы с ним.

Если самостоятельно VS Code не нашла компилятор, то нужно редактировать файл c_cpp_properties.json, который идет вместе с расширением. Именно в данном файле настраивается путь к includePath

Подробнее по ссылке на официальном сайте. Ссылка актуальна на 2020 год.

https://code.visualstudio.com/docs/cpp/configure-intellisense-crosscompilation

Кликаем по предложенной подсказке.

Текст файла примерно такой:

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "shell: gcc.exe build active file",
            "command": "C:\MinGW\bin\gcc.exe",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}\${fileBasenameNoExtension}.exe"
            ],
            "options": {
                "cwd": "C:\MinGW\bin"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
     }
   ]
}

Выглядит страшно, как и любой развернутый JSON

Гайд на официальном сайте vscode говорит о том, что этого достаточно, а если что-то идет не так, то отсылают почитать про функционал task.json. К сожалению, если оставить в таком виде, то собирать многофайловые проекты будет невозможно.

Если в вашем проекте будет НЕ больше одного файла, можете пропустить дальнейший текст и перейти к настройке дебаггера. Если планируется работать с несколькими файлами – рекомендую проделать дальнейшие манипуляции.

JSON – это текстовое представление данных/объектов (в основном в JS).
Обычно используется для передачи данных в парах Клиент-Сервер.
Массивы обозначаются квадратными скобками []
Ячейки обозначаются фигурными скобками {}
Обычная запись представляет собой пару ключ-значение через двоеточие:
{ “Ключ” : “Значение” }
Значение может быть массивом, ячейкой, массивом ячеек и т.д. – ограничений нет.

Коротко про JSON

Поле tasks содержит массив ( [массив] ), который состоит из ячеек отделенных фигурными скобками и запятыми ( [ {ячейка 1}, {ячейка 2}, {ячейка 3} ] ). В нашем случае этот массив содержит одну ячейку.

Создадим еще один элемент в массиве задач (task). Нужно скопировать все что есть в квадратных скобках (task[ вот это ]) и вставить через запятую в конце первой ячейки массива.

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "shell: gcc.exe build active file",
            "command": "C:\MinGW\bin\gcc.exe",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}\${fileBasenameNoExtension}.exe"
            ],
            "options": {
                "cwd": "C:\MinGW\bin"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        },
        {
            "type": "shell",
            "label": "shell: gcc.exe build active file",
            "command": "C:\MinGW\bin\gcc.exe",
           "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}\${fileBasenameNoExtension}.exe"
            ],
            "options": {
                "cwd": "C:\MinGW\bin"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

Файл должен выглядеть примерно как указано выше. Следите за скобками и запятыми – если где-то будет ошибка VS Code сообщит. Удаляем ячейку “group” на строках 20-23. Этот параметр отвечает за выбор компилятора, который будет запущен по-умолчанию.

Нас сейчас больше всего интересуют строки с 27 по 31.

Изменим значение ячейки “label” на 27 строке на любое название. Пусть будет build c project. Именно по этому имени мы сможем понять какой именно компилятор сейчас выбран.

Ячейка “command” – это команда, которая будет передана в терминал/консоль для старта компиляции. Как мы видим, все правильно, это путь к gcc.exe.

Ячейка “args” – это список аргументов, который будет передан после команды. Не пугайтесь, мы уже это делали. Чуть ранее мы узнавали версию gcc путем передачи аргумента -version.

  1. “-g” указывает компилятору на необходимость вставлять в готовое приложение отладочную информацию – номера строк, имена переменных и т.д. Необходимо для корректной работы дебаггера (отладчика) GDB;
  2. Следующим аргументом идёт файл или список файлов. “${file}” означает текущий файл. То есть компилятору будет передан только один файл. Мы хотим, чтобы сюда входили все файлы из определенной директории. Да, одним из решений будет вписывать сюда каждый созданный .c файл, но разве это удобно? Значит записываем сюда конструкцию: Из этой директории, взять все .c-файлы. Получится следующее: “${fileDirname}/**.c
  3. Аргумент вывода файла
  4. Путь вывода скомпилированного приложения.

В итоге, добавленная нами часть будет выглядеть следующим образом:

         {
            "type": "shell",
            "label": "build c project",
            "command": "C:\MinGW\bin\gcc.exe",
            "args": [
                "-g",
                "${fileDirname}/**.c",
                "-o",
                "${fileDirname}\${fileBasenameNoExtension}.exe"
            ],
            "options": {
                "cwd": "C:\MinGW\bin"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

Подробнее про task.json

https://code.visualstudio.com/docs/editor/tasks

Настройка отладчика

Теперь настроим дебаггер или отладчик. Переходим в наш файл с кодом, далее Run > Add Configuration…

Выбираем окружение GDB

Выбираем Сборка и отладка активного файла

Если возникла ошибка и открылось окно, нажмите на нем Abort. Это лишь значит, что не удалось собрать приложение – может быть синтаксическая ошибка.

Далее откроется файл launch.json

Для тех, кто добавлял свой task: Изменим значение preLaunchTask на то название, которое придумали для своего компилятора. В моем случае – это “build c project“. Чтобы не было путаница стоить изменить и поле “name“. Можете как и прошлом примере добавить еще одну конфигурацию запуска в массив конфигураций, оставив первоначальную без изменений.

Запускаем приложение

Снова переходим в созданный файл с кодом и выбираем Terminal > Run Build Task…

Эта команда проведет все шаги компиляции приложения и создаст в целевой папке исполняемый файл с расширением .exe

На картинке выше красным подчеркнут выпадающий список открытых терминалов (без паники – это как несколько cmd-консолей или терминалов в линуксе). Синим (правее красной линии, видно плохо) подчеркнуты элементы управления списком терминалов – их можно добавить, удалить или поставить парочку рядом.

Как мы видим, процесс компиляции завершился без ошибок и в списке файлов проекта появился .exe.

Создадим новый терминал.

Как мы видим, изменился порядковый номер нового терминала. Также видно, что мы находимся в папке с проектом. Отсюда можно вызвать наше скомпилированное приложение. Можно начать набирать его имя и нажать Tab и сработает автодополнение. На каждое следующее нажатие терминал предложит различные подходящие варианты под то, что имелось ввиду. Если предложить нечего – ничего не произойдет.

Вызовем наше приложение. В моем случае:

> .hellowd_main.exe

Замечательно, вывод сработал как надо.

Теперь инициируем отладку/дебаггинг этого приложения, чтобы посмотреть как это работает.

Установим “Breakpoint” или точку останова. Все как в классических IDE.

Запускаем отладку Run > Start Debugging или f5

Выполнение программы было приостановлено в том месте, которое мы пометили точкой останова.

Открылось другое окно редактора, которое специально подготовлено для работы в режиме отладки. В левой части окна появилось четыре секции:

  • VARIABLES все переменные
  • WATCH сюда, через знак плюса можно добавлять переменные, функции и т.д. по имени
  • CALL STACK стек вызовов функции. В общих чертах – функции часто вызываются в теле других функций.
  • BREAKPOINTS все точки останова

Текущая выполняемая строка подсвечивается и имеет желтый указатель строки

Управление ходом отладки программы тоже удобное и классическое.

  • Продолжить
  • Сделать шаг
  • Пройти “внутрь” текущей строки
  • Выйти на уровень выше
  • Перезапуск отладки
  • Остановка отладки

Удачного освоения инструмента

MinGW is a native C/C++ compiler(GCC) which have free distributable import libraries and header files for building native Windows applications. In this tutorial, we are going to install MinGW for C/C++. These are a few steps that we have to perform to successfully install MinGW on our device. 

How to Install the MinGW Tools for C/C++?

Step 1: Go to the MinGW website and click on Download. It will start downloading in 5 seconds.

MinGW

Step 2: Double click and open the exe MinGW file and click install. It will automatically start downloading all the setups for the MinGW. 
Step 3: After all of the setup click Continue. Now the MinGW installation manager will pop up.

MinGW installation manager

Step 4: In the installation manager right click on every option and then click Mark for Installation

Mark for installation

Step 5: In the Installation, option-click Apply changes. And then select Apply. It will start downloading all the files. It will take 5-6 minutes. After finishing click on Close. 

Apply changes

How to Change Environment Variables for MinGW

After successful installation of MinGW, next step is to change the environment location for MinGW.

Step 1:  Go to the C drive on your device and search for the MinGW folder. And in the MinGW folder go to the bin folder and copy its path.

Copy path

Step 2: Go to the control panel then go to System then Advanced system settings and then Environment variables. 

Go to control panel

Step 3: In the system variables search for path and then select Edit. Now add a new path to it by clicking New. Now paste the path and click ok. 

Edit path

This marks the complete installation of MinGW in the system.

Another method to change Environment Variable for MinGw.

Step 1:  Go to the C drive on your device and search for the MinGW folder. And in the MinGW folder go to the bin folder and copy its path.

Step 2: Now go to this pc and right click there and click on show more properties and click on properties pointed by the arrow.

Step 3: Now click on Advanced system setting.

Step 4: Now click on environmental variables.

Step 5: Now in system variables click on path and click on edit button.

Step 6: Now click on new button and paste the copied path there as shown in photo.

Now click on “ok” button of step 6, 5 and 4. and then close all the windows and restart your pc.

This marks the complete installation of MinGW in the system.

MinGW is a native C/C++ compiler(GCC) which have free distributable import libraries and header files for building native Windows applications. In this tutorial, we are going to install MinGW for C/C++. These are a few steps that we have to perform to successfully install MinGW on our device. 

How to Install the MinGW Tools for C/C++?

Step 1: Go to the MinGW website and click on Download. It will start downloading in 5 seconds.

MinGW

Step 2: Double click and open the exe MinGW file and click install. It will automatically start downloading all the setups for the MinGW. 
Step 3: After all of the setup click Continue. Now the MinGW installation manager will pop up.

MinGW installation manager

Step 4: In the installation manager right click on every option and then click Mark for Installation

Mark for installation

Step 5: In the Installation, option-click Apply changes. And then select Apply. It will start downloading all the files. It will take 5-6 minutes. After finishing click on Close. 

Apply changes

How to Change Environment Variables for MinGW

After successful installation of MinGW, next step is to change the environment location for MinGW.

Step 1:  Go to the C drive on your device and search for the MinGW folder. And in the MinGW folder go to the bin folder and copy its path.

Copy path

Step 2: Go to the control panel then go to System then Advanced system settings and then Environment variables. 

Go to control panel

Step 3: In the system variables search for path and then select Edit. Now add a new path to it by clicking New. Now paste the path and click ok. 

Edit path

This marks the complete installation of MinGW in the system.

Another method to change Environment Variable for MinGw.

Step 1:  Go to the C drive on your device and search for the MinGW folder. And in the MinGW folder go to the bin folder and copy its path.

Step 2: Now go to this pc and right click there and click on show more properties and click on properties pointed by the arrow.

Step 3: Now click on Advanced system setting.

Step 4: Now click on environmental variables.

Step 5: Now in system variables click on path and click on edit button.

Step 6: Now click on new button and paste the copied path there as shown in photo.

Now click on “ok” button of step 6, 5 and 4. and then close all the windows and restart your pc.

This marks the complete installation of MinGW in the system.

GOAL

To install g++ in Windows10 and compile a c++ file. g++ is included in

What is g++?

g++ is the command to compile c++ and the name of C++ compiler included in GCC, the GNU Compiler Collection. You can use g++ on GNU such as Cygwin and MinGW.

Method

I’ll use MinGW

Get mingw-get-setup.exe

Access the MinGW web site and go to the Downloads page. Click and downloads mingw-get-setup.exe.

from MinGW web site

Run the downloaded file.

Click “Install” an “Continue” with your preference.

Install Basic MinGW and GCC(g++).

Mark “mingw32-base-bin” and “mingw32-gcc-g++-bin” on MinGW Installation Manager.

from MinGW Installation Manager

Click Installtion > Apply Changes

from MinGW Installation Manager

Export path

Add C:MinGWbin into environment variables Path.

Operation check

Open Command Prompt and input the command “g++ -v”.

Command to compile C++ file

g++ helloWorld.cpp

You can see command line options at the die.net g++(1) – Linux man page.

Appendix

Additionally install msys if you’d like to use shell with MinGW.

MinGW (“Minimalist GNU for Windows”) is a complete runtime environment for gcc to support binaries native to Windows 64-bit and 32-bit operating systems. With MinGW we can build C programs for windows. This tool is also required to build C-programs for microcontrollers. We will be seeing how to write codes for microcontrollers without using the any IDE. And we will use the MinGW compiler along with the microcontroller family toolchain to build the code. We will install mingw and configure it for running the “make” files

This post is the first step in the complete build process. In this post, we will look at installing mingw and adding it to the environment variables.

1.1 Download MingGW

It contains Make that we will be using in Command Prompt on Windows 10.

1.2 Install MinGW

We will now see how to install minGW. In this step, we will look at the important options that need to be selected.

Keep the Installation Directory the same as shown below.

install mingw

1.2.1 Navigate to your Desktop

Open MinGW Installer. Select Basic Setup, navigate to Packages and Right click on “mingw-developer-toolkit-bin”, “mingw32-base-bin” and “msys-base-bin” Packages and select Mark for Installation.

install mingw - select options

1.2.2 Navigate to the Top left corner and Left click on Installation then click Apply Changes.

1.2.3 The packages should now be Green (if not, just repeat the process), if they are successfully installed then close the Installation Manager.

install mingw - installed componenets

1.3 Rename to Make

Navigate to C:MingGWbin. Rename “mingw32-make” to “make”. This will make it easier to use Make in the Command Prompt.

1.3.1 Let’s add Make for usage in Command Prompt.

Press the “Windows Icon” on your keyboard, search and open “Edit the system environment variables”.

1.3.2 Click on “Environment Variables

1.3.2 Under “System variables”, scroll down to “Path” and double-click.

1.3.3 Click on “New” and add the location “C:MingGWbin” to environment variable and press “OK”.

1.4 Testing Make

Press the “Windows Icon” on your keyboard, search and open “Command Prompt”.

1.4.1 Type “make –version” to confirm that it works. Recheck Step 1.3 – 1.4 if it doesn’t work.

Asked
11 years, 9 months ago

Viewed
134k times

I am using Windows XP. I am trying to add a new library to Dev-C++. For that, I need to install MinGW and then I have been instructed to add the bin directory of MinGW to my system path. But, I don’t know how to do it. Please guide me (step by step) to add this to my system path.

Peter Mortensen's user avatar

asked Apr 20, 2011 at 15:58

niro's user avatar

To change the path on Windows XP, follow these instructions, and then add the directory where you install MinGW plus bin. Example: if you install MinGW in C: then you have to add C:mingwbin to your path

Just for completeness here are the steps shown on the link:

  1. From the desktop, right-click My Computer and click Properties.
  2. In the System Properties window, click on the Advanced tab.
  3. In the Advanced section, click the Environment Variables button.
  4. Finally, in the Environment Variables window, highlight the Path variable in the Systems Variable section and click the Edit button. Add or modify the path lines with the paths you wish the computer to access. Each different directory is separated with a semicolon as shown below.

    C:Program Files;C:Winnt;C:WinntSystem32;c:mingwbin

Peter Mortensen's user avatar

answered Apr 20, 2011 at 16:18

Dave's user avatar

DaveDave

5325 silver badges8 bronze badges

2

Понравилась статья? Поделить с друзьями:
  • Как добавить блютуз в скрытые значки windows 10
  • Как добавить microsoft store в windows 10 enterprise ltsc
  • Как добавить microsoft print to pdf windows 10
  • Как добавить блютуз в диспетчер устройств на windows 10
  • Как добавить linux в windows boot manager