Get Started With C++ And Mingw-w64 In Visual Studio Code

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, run, and debug a Hello World program.

This tutorial does not teach you about GCC, GDB, minGW-w64, or the C++ language. For those subjects, there are many good resources available on the Web.

If you have any problems, feel free to file an issue for this tutorial in the VS Code documentation repository.

Prerequisites

To successfully complete this tutorial, you must do the following steps:

  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

Installing the MinGW-w64 toolchain

Get the latest version of MinGW-w64 via MSYS2, which provides up-to-date native builds of GCC, MinGW-w64, and other helpful C++ tools and libraries. This will provide you with the necessary tools to compile your code, debug it, and configure it to work with IntelliSense.

To install the MinGW-w64 toolchain, check out this video or follow the steps below:

  1. You can download the latest installer from the MSYS2 page or use this direct link to the installer.

  2. Run the installer and follow the steps of the installation wizard. Note that MSYS2 requires 64 bit Windows 8.1 or newer.

  3. In the wizard, choose your desired Installation Folder. Record this directory for later. In most cases, the recommended directory is acceptable. The same applies when you get to setting the start menu shortcuts step. When complete, ensure the Run MSYS2 now box is checked and select Finish. This will open a MSYS2 terminal window for you.

  4. In this terminal, install the MinGW-w64 toolchain by running the following command:

    gcc --version g++ --version gdb --version

    You should see output that states which versions of GCC, g++ and GDB you have installed. If this is not the case:

    1. Make sure your PATH variable entry matches the MinGW-w64 binary location where the toolchain was installed. If the compilers do not exist at that PATH entry, make sure you followed the previous instructions.
    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.
      • If on compilation you are getting the "The value of miDebuggerPath is invalid." message, one cause can be you are missing the mingw-w64-gdb package.

    Create a Hello World app

    First, lets get a project set up.

    1. Launch a Windows command prompt (Enter Windows command prompt in the Windows search bar).
    2. Run the following commands. These will create an empty folder called projects where you can place all your VS Code projects. There, the next commands will create and navigate to a subfolder called helloworld. From there, you will open helloworld directly in VS 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 selecting File > Auto Save. You can find out more about the other views in the VS Code User Interface documentation.

    Note: When you save or open a C++ file, you may see a notification from the C/C++ extension about the availability of an Insiders version, which lets you test new features and fixes. You can ignore this notification by selecting the X (Clear Notification).

    Explore IntelliSense

    IntelliSense is a tool to help you code faster and more efficiently by adding code editing features such as code completion, parameter info, quick info, and member lists.

    To see IntelliSense in action, hover over vector or string to see their type information. If you type msg. in line 10, you can see a completion list of recommended member functions to call, all generated by IntelliSense:

    Statement completion IntelliSense

    You can press the Tab key to insert a selected member. If you then add open parenthesis, IntelliSense will show information on which arguments are required.

    If IntelliSense is not already configured, open the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)) and enter Select IntelliSense Configuration. From the dropdown of compilers, select Use gcc.exe to configure. More information can be found in the IntelliSense configuration documentation.

    Run helloworld.cpp

    Remember, the C++ extension uses the C++ compiler you have installed on your machine to build your program. Make sure you have completed the "Installing the MinGW-w64 toolchain" step before attempting to run and debug helloworld.cpp in VS Code.

    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

    Congratulations! You've just run your first C++ program in VS Code!

    Understanding tasks.json

    The first time you run your program, the C++ extension creates a tasks.json file, which you'll find in your project's .vscode folder. tasks.json stores your build configurations.

    Your new tasks.json file should look similar to the JSON below:

    "group": { "kind": "build", "isDefault": true },

    with this:

    { "configurations": [ { "name": "C/C++: g++.exe build and debug active file", "type": "cppdbg", "request": "launch", "program": "${fileDirname}\\${fileBasenameNoExtension}.exe", "args": [], "stopAtEntry": false, "cwd": "${fileDirname}", "environment": [], "externalConsole": false, "MIMode": "gdb", "miDebuggerPath": "C:\\msys64\\ucrt64\\bin\\gdb.exe", "setupCommands": [ { "description": "Enable pretty-printing for gdb", "text": "-enable-pretty-printing", "ignoreFailures": true }, { "description": "Set Disassembly Flavor to Intel", "text": "-gdb-set disassembly-flavor intel", "ignoreFailures": true } ], "preLaunchTask": "C/C++: g++.exe build active file" } ], "version": "2.0.0" }

    In the JSON above, program specifies the program you want to debug. Here it is set to the active file folder (${fileDirname}) and active filename with the .exe extension (${fileBasenameNoExtension}.exe), which if helloworld.cpp is the active file will be helloworld.exe. The args property is an array of arguments to pass to the program at runtime.

    By default, the C++ extension won't add any breakpoints to your source code and the stopAtEntry value is set to false.

    Change the stopAtEntry value to true to cause the debugger to stop on the main method when you start debugging.

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

    Adding additional C/C++ settings

    If you want more control over the C/C++ extension, you can create a c_cpp_properties.json file, which will allow you to change settings such as the path to the compiler, include paths, C++ standard (default is C++17), and more.

    You can view the C/C++ configuration UI by running the command C/C++: Edit Configurations (UI) from the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)).

    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 .vscode\c_cpp_properties.json. If you open that file directly, it should look something like this:

    pacman -S --needed base-devel mingw-w64-x86_64-toolchain

    When adding the MinGW-w64 destination folder to your list of environment variables, the default path will then be: C:\msys64\mingw64\bin.

    MinGW 32-bit

    If you need a 32-bit version of the MinGW toolset, consult the Downloading section on the MSYS2 wiki. It includes links to both 32-bit and 64-bit installation options.

    Next steps

    • Explore the VS Code User Guide.
    • Review the Overview of the C++ extension.
    • Create a new workspace, copy your .vscode JSON files to it, adjust the necessary settings for the new workspace path, program name, etc. and start coding!
    12/14/2023

Từ khóa » Cài đặt Gcc