Use VSCode to debug simple C++ code in Linux environment

This article will introduce how to use the GCC C++ compiler (g++) and GDB debugger (gdb) in the Linux environment in VSCode by demonstrating the compilation and debugging process of a simple C++ code.

Regarding GCC, g++, gcc, and gdb, I will not introduce them in detail here. If you are interested, you can refer to another article: Detailed explanation of the whole process of preprocessing, compiling, assembling, and linking of C/C++ code . There are detailed explanations in it.

To understand the content of this article, you only need to know that g++ is used to compile C++ code, and gdb is used to debug C++ code.

The content of the sample code is as follows:

// hello.cpp
#include <iostream>
using namespace std;
int main(){
    
    
	cout << "Hello, VSCode!" << endl;
    return 0;
}

1. Compile and debug simple C++ code in terminal command line mode

If you don't consider the VSCode editor, compiling and debugging a simple C++ code in the Linux environment can only be implemented through the command line. The specific process is divided into two steps:

  1. Step 1 : Pass *.cppthe source code file through g++the compiler to generate a debuggable executable binary file:
g++ -g hello.cpp -o hello

Instruction analysis:

  • In order to be able to use gdb debugging, you need to add at compile time-g
  • hello.cpp: The name of the source file to be compiled
  • -o hello: Specify the generated executable file name ashello
# 运行 hello 的结果:
./hello
Hello, VSCode!
  1. Step 2 : Call the gdb debugger to debug the executable file:
gdb hello

The debugging process is as follows:
gdb debugging process

  • If you want to compile and debug C++ code in VSCode, all you need to do is configure and complete the above two steps.

2. Compile and debug C++ code through VSCode

Main reference:

2.1 Prerequisites

  1. The "C/C++ plugin" in VSCode has been installed (directly search for "C++" in the VSCode extension store)

C/C++ plugin

  1. The g++ compiler is installed. You can check whether g++ is installed in the terminal
g++ -v

If the version information can be output, it is installed. If not, install it with the following command:

sudo apt-get update
sudo apt-get install build-essential gdb

2.2 Configure tasks.json

Open the sample code folder in VSCode,

folder

  1. In VSCode's main menu, select Terminal>Configure Default Build Task
  2. A drop-down menu appears showing various predefined compilation tasks for the C++ compiler. Select C/C++: g++ build active file (if Chinese is configured, "C/C++: g++ build active file" will be displayed )
  3. After selection, vscode will automatically generate a .vscodefolder and tasks.jsonfile . At this time, the code folder structure is as follows:
    tasks.json
    tasks.jsonthe content is as follows:
{
    
    
	"version": "2.0.0",
	"tasks": [
        {
    
    
            "type": "cppbuild",
            "label": "C/C++: g++ 生成活动文件",
            "command": "/usr/bin/g++",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
    
    
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
    
    
                "kind": "build",
                "isDefault": true
            },
            "detail": "编译器: /usr/bin/g++"
        }
    ]
}

tasks.jsonThe role is to tell VSCode how to compile the program

In this article, it is hoped to call the g++ compiler to create an executable file from the cpp source code, thus completing the first step of compilation and debugging mentioned in Section 1.

"command"As can be seen from the sum of tasks.json "args", the following commands are actually executed:

/usr/bin/g++ -g ${file} -o ${fileDirname}/${fileBasenameNoExtension}

in,

  • ${file}: The current active file (that is, the file currently viewed by vscode), here ishello.cpp
  • ${fileDirname}/${fileBasenameNoExtension}: Here is the current directoryhello
  • For variable names in VSCode, please refer to: VSCode Variables Reference

2.3 Execute compilation

After the tasks.json file is configured in section 2.2, VSCode knows that the cpp file should be compiled with the g++ compiler, and the compilation can be performed as follows:

  1. Go back to the active file hello.cpp (very important, otherwise the variables ${file} and ${fileDirname} will be wrong)
  2. Press the shortcut key ctrl+shift+Bor select Run from the menu: Terminal -> Run Build Task to execute the compilation process specified in tasks.json
  3. After the compilation task is completed, a terminal prompt will appear. For a successful g++ compilation, the output is as follows:
    insert image description here
    After this step is completed, an executable file appears in the code directory hello.
  4. (Optional) Personalized modification of tasks.json
    You can modify tasks.json to meet some specific needs, such as "${file}"replacing “${workspaceFolder}/*.cpp”to build multiple C++ files; “${fileDirname} /${fileBasenameNoExtension}”replacing with a hard-coded file name (eg “hello.out”) to modify the output file name

2.4 Debug hello.cpp

After completing the above compilation configuration, you can debug hello.cppit:

  1. Go back to hello.cpp and make sure it is the active file
  2. set a breakpoint
  3. From the top right buttons, select Debug C/C++ file
    insert image description here
  4. Then start the debugging process, you can single-step, add monitoring, and so on.

2.5 Personalized configuration launch.json

According to the process in section 2.4, a code can be easily debugged .cpp, but in some cases, you may want to customize the debugging configuration, such as specifying the command parameters to be passed to the program at runtime . In this case we can launch.jsondefine a custom debug configuration in .

Here are the steps to configure the debugging process :

  1. From the main menu, select Run > Add Configuration… and a launch.jsonfile will be generated
  2. launch.jsonClick "Add Configuration" in the lower right corner of the file , select "(gbd) start" , the content of the file is as follows:
{
    
    
    "version": "0.2.0",
    "configurations": [
        {
    
    
            "name": "(gdb) 启动",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}/${fileBasenameNoExtension}",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${fileDirname}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "setupCommands": [
                {
    
    
                    "description": "为 gdb 启用整齐打印",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                },
                {
    
    
                    "description": "将反汇编风格设置为 Intel",
                    "text": "-gdb-set disassembly-flavor intel",
                    "ignoreFailures": true
                }
            ],
            "miDebuggerPath": "/usr/bin/gdb",
            "preLaunchTask": "C/C++: g++ 生成活动文件"
        }
    ]
}

The role here launch.jsonis to tell VSCode how to call the gdb debugger.

If you want to add parameters when debugging/running the program, just add the parameters to "args"the options.

2.6 Summary

To compile and debug a simple .cpp file in VSCode, all you need to do is:

  1. Call g++ in tasks.json to generate an executable binary file
  2. Call gdb in launch.json to debug the generated executable file

2.7 Reusing C++ Configuration

The above process has completed the configuration of debugging C++ code in the Linux environment in VSCode, but it is only applicable to the current workspace. If you want to reuse this configuration in other project folders, you only need to copy tasks.jsonthe and launch.jsonfiles to the directory under the new folder .vscode, and then change the names of the corresponding source files and executable files as needed.

3. Reference Tutorial

  1. Detailed explanation of using vscode to compile, run and debug C/C++ under Linux
  2. VSCode Official Tutorial: Using C++ on Linux in VS Code
  3. VSCode Variables Reference

Guess you like

Origin blog.csdn.net/hypc9709/article/details/129413482