VSCode runs c++ program (operation + detailed explanation + json file configuration detailed explanation)

Preface: Because the quality of online tutorials varies, I felt very confused when I first came into contact with this thing. I hereby write this blog to help my friends solve the problem.

Table of Contents

1. Operation details

1Download VSCode code editor

2Install C/C++ extension

3Install the MinGW-w64 compiler

4Add path

5 Test whether the addition is successful

6After the addition is successful, proceed to configure the json file.

2. Detailed explanation of json file configuration

1 launch.json file

2 tasks.json file

3 c_cpp_properties.json file

3. Some cases

1Run c++ program

2Use an external terminal

3Reference external header files

4. When using an external terminal without adding system(“pause”), how to close the terminal within seconds without running it?

5 Modify the compiler encoding


1. Detailed operation part

1Download VSCode code editor

Just download the corresponding version for your computer from the official website

VSCode is just a code editor and not an IDE (integrated development environment), so if you want to run the program, you need other steps

VSCode official website link: Visual Studio Code – Code Editing. RedefinedVisual Studio Code is a code editor redefined and optimized for building and debugging modern web and cloud applications. Visual Studio Code is free and available on your favorite platform – Linux, macOS, and Windows. icon-default.png?t=N7T8https://code.visualstudio.com/

2InstallC/C++ extension

Open VSCode, find the extension in the left column (it should be English initially), click in, search for and install C/C + + and Chinese (Simplified) (Simplified Chinese) Language in the extension Pack for Visual Studio (Chinese version is more friendly), you can choose to install the C/C++ Extension Pack extension

C/C + + Extension Pack This extension includes the C/C + + extension. It also includes the CMake Tools extension. This extension It is used for advanced work such as packaging in the future of C++. It is not used for the time being.

The C/C + + extension includes functions such as code completion IntelliSense (intelligent sensing). For example, after entering an instance of a class, it can automatically display the member functions for you later.

3Install MinGW -w64 compiler

C++ programs cannot be run directly like python, so a compiler is required to compile the .cpp file into a binary executable .exe file

Compiler resource link: MinGW-w64 – for 32 and 64 bit Windows – Browse Files at SourceForge.netA complete runtime environment for gccicon-default.png?t=N7T8https://sourceforge.net /projects/mingw-w64/files/

The upper part of this download resource webpage is the source code of the compiler. What we want to download is the compiled binary file (executable file). You need to scroll down, find the part as shown below and install it. You can see the version selection for more information. Link content below

Version difference introduction link: MinGW-w64 installation and use_Personal test and effective-CSDN blog article has been viewed and read 1.9k times, liked 3 times, and collected 4 times. MinGW-w64 is a GNU compiler suite that runs on Windows systems and supports compilation of C and C++ languages. It includes the GCC compiler, GNU Binutils, and some other tools. In MinGW-w64_mingw-w64 https://blog.csdn.net/qq_35401605/article/details/131249070

The download is a zip package that needs to be decompressed. This decompression step is actually equivalent to installation in a broad sense.

MinGW-w64 and MinGW compiler are Microsoft’s modified versions of the GCC compiler. With or without 64, it means that compilation of 64-bit programs is not supported.

4Add path

In the environment variables, system variables, and path variables, add the path to the bin folder in the decompressed file.

In the bin folder you can see the g++.exe and gcc.exe files. This is the compiler program we need. The purpose of adding the path is not to enter the absolute path when calling the program, but only to enter g++ .exe to call the program. After adding the path, the system will first search for the required program in these specified folders.

5 Test whether the compiler is added successfully

Test whether the compiler is added successfully on the command line. Enter “gcc –version” or “g++ –version” on the command line.

After 6 is added successfully, proceed to configure the json file

2. Detailed explanation of json file configuration

The json files we need include launch.json file, tasks.json file, (c_cpp_properties.json)

launch.json is used to run .exe files, tasks.json is the specified automatic task before running, which compiles .cpp files into .exe files, and c_cpp_properties.json is extendedC/C++ Some settings in Extension Pack

We create a .vscode folder under the open workspace, that is, the folder currently opened by cscode, and add these files to it. The file content is as follows

1 launch.json file

In addition to code editing, vscode can also run and debug the code, and this file is essential for code running and debugging. In launch.json we will specify the name of the running program, the parameters passed and other information, as follows is an example

{
    "version": "0.2.0",
    "configurations": [
      {
        "name": "VSCode debugger(gcc-gdb)",
        "type": "cppdbg",
        "request": "launch",
        "program": "${workspaceFolder}\output\${fileBasenameNoExtension}.exe",
        "cwd": "${workspaceFolder}",
        "preLaunchTask": "C/C++ compiler",
        "miDebuggerPath": "E:\Study\mingw64\bin\gdb.exe",
        "MIMode": "gdb"
      },
      {
        "name": "visual studio debugger",
        "type": "cppvsdbg",
        "request": "launch",
        "program": "${workspaceFolder}\output\${fileBasenameNoExtension}.exe",
        "cwd": "${workspaceFolder}",
        "preLaunchTask": "C/C++ compiler"
      }
    ]
}

The json file consists of two curly brackets at the beginning and the end. The parameters are arranged in the form of keyword: value. A version is defined in the outermost layer for specifying the configuration. The version of the file (cannot be modified), configuration is the specific configuration, and the value is enclosed in brackets

There are two configurations in my json file. One is named VSCode debugger (gcc-gdb) and the other is visual studio debugger. They are enclosed in curly brackets and separated by commas. The following is the keyword-by-keyword information in each configuration. :

“name”: Configuration name (can be changed, necessary), the name displayed when calling
“type”: configuration type (only selected individually, necessary), cppdbg is the debugger that comes with downloading gcc, and is also in the bin folder, cppvsdbg is the debugger in my visual studio
“request”: request (only two options, necessary), you can only choose launch or attach, corresponding to whether to open a new program or attach it to another program
“program”: The program to be run (necessary). Remember to use the correct path such as an absolute path. Of course, you can also use the vscode keyword to replace the path. This can be searched by yourself.
“cwd”: target working directory (optional)
“preLaunchTask”: This keyword is more critical, because the C++ program must be compiled into an exe file before it can be run, so this keyword is used to specify the automatic execution task before running the program, and the value is filled with the task to be pre-processed Name, that is, the name in tasks.json created later

“miDebuggerPath”: debugger path (not necessary), because the system can automatically search for it without filling it in. If the path was not added correctly before, I don’t know if it can be found.
“MIMode”: debugger mode (optional)

The launch.json file also has other keywords used to specify different content. Please see the official documentation for details.

https://code.visualstudio.com/docs/editor/debuggingicon-default.png?t=N7T8https://code.visualstudio.com/docs/editor/debugging

2 tasks.json file

Because C++ requires compilation, if you want to run a C++ program, you must first compile it into an exe file. Launch.json runs the exe file, and tasks.json is the specified automatic task before running. Compile the cpp file into an exe file. The example is as follows:

{
    "tasks": [
        {
            "type": "shell",
            "label": "C/C++ compiler",
            "command": "E:\Study\mingw64\bin\g + + .exe",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${workspaceFolder}\output\${fileBasenameNoExtension}.exe"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "detail": "compiling task",
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ],
    "version": "2.0.0"
}

The format is similar to the previous json file. The following is a keyword-by-keyword explanation:

type: required, only two options

label: necessary, must be the same as the value of preLaunchTask in launch.json

command: necessary, the program called by this task, here calls g++ to compile this file

args: necessary, command line parameters, you need to specify -g debuggable and -o output as exe file, which is equivalent to entering g++ -g XX.cpp -o XX.exe on the command line

options: optional, some options

problemMatcher: necessary, specify what to do if an error occurs

detail: optional, some detailed information

group: optional, task group configuration

The outermost tasks and versions are necessary and cannot be changed.

3 c_cpp_properties.json file

This file mainly tells IntelliSense (code completion tool) some things and some settings. I will not expand them here. Search by yourself. Example:

{
    "configurations": [
        {
            "name": "Win32",
            "compilerPath": "E:\Study\mingw64\bin\g + + .exe",
            "intelliSenseMode": "windows-gcc-x64",
            "includePath": [
                "${workspaceFolder}/**"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "cStandard": "c17",
            "cppStandard": "c++17",
            
            "windowsSdkVersion": "10.1.22621.0"
        }
    ],
    "version": 4
}

3. Some cases

1run c++ program

After the above files are set up, you can create a new test.cpp file and enter the following code:

#include <iostream>

using namespace std;

int main(void)
{
    cout << "Hello, World!" << endl;
    system("pause");
    return 0;
}

Then click the small triangle in the upper right corner, and then select the debug configuration (be sure to select the configuration we just set, which is the VSCode debugger (gcc-gdb) in the picture)

Then the output will be displayed in the terminal below

2Use external terminal

Add this setting “console”: “externalTerminal” or “externalConsole”: false in a configuration of launch.json

3Reference external header files

1Add the path of the header file in “includePath” of c_cpp_properties.json and tell Intelligent Sense (code completion tool)

2. Add “-I” and “(corresponding file path)” to the args of tasks.json to tell the compiler where to find the header file.

4When using an external terminal and not adding system(“pause”), how to shut down the terminal in seconds without running it Terminal

Let launch.json not run the compiled exe file, but run the cmd.exe file, and then pass parameters to the cmd program to tell it to run the compiled exe file, and automatically add system(“pause”) at the end of the file, do this It can achieve non-second shutdown, but it cannot be debugged. The reason must be known to you who are smart.

5Modify compiler encoding

The terminal outputs garbled characters because the encoding of the string output in the code is inconsistent with the encoding of the string compiled by the compiler. Therefore, a command line parameter “-fexec-charset=gbk” should be added to the args of tasks.json. Without parameters, the default is UTF-8 encoding, gbk is the encoding of Simplified Chinese