vscode对C++程序进行调试

调试helloworld

先建立一个文件夹然后在文件夹,创建一个test.cpp 写下一下内容。

# include <iostream>

int main(int argc, char* argv[]){
    
    for(int i = 0 ; i < argc ; i++){
        std::cout << argv[i] << std::endl;
    }

    std::cout << "hello" << std::endl;
    return 0;
}

然后再写一个最简单的CMakeLists 内容如下:

cmake_minimum_required(VERSION 3.2)
project(hello)
set(CMAKE_BUILD_TYPE DEBUG)

add_executable(hello test.cpp)

cmake的 CMAKE_BUILD_TYPE 这个一定要大写, 不要问我为什么。。。此处流泪…
之后建立 build 目录 cmake…
然后make
生成了 hello程序了,这个时候就可以开始调试了

首先点击vscode的调试按钮然后生成调试所需要的 launch.json 文件。
这是一个json文件,用于告诉vscode该如何调试这个程序

{
    // 使用 IntelliSense 了解相关属性。 
    // 悬停以查看现有属性的描述。
    // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "(gdb) 启动",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceFolder}/build/hello",
            "args": ["中国 ", " 是一个伟大的国家"],
            "stopAtEntry": false,
            "cwd": "${fileDirname}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "为 gdb 启用整齐打印",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ]
        }
    ]
}

修改 program 字段,这个字段用于告诉 vscode该调试哪一个程序。
args 字段用于设置程序的传入参数

然后 运行–》启动调试 就可以进入调试界面了 如图所示:
在这里插入图片描述
现在就可以图形画的进行调试了。

调试先生成可执行程序

刚刚进行调试的时候是现将程序进行编译了,然后才进行的调试。这样子很麻烦,可以直接加一个任务然后让调试前先自动生成。
在 launch.json 中加入 preLaunchTask 选项, pre意思是 前, 就是说在调试前先执行这条命令。
例如在之前的 launch.json 加入: "preLaunchTask": "build"
之后创建一个tasks.json, 创建方法鼠标在vs界面中 右键–> 命令面板–> 选择task 。之后会自动生成模板
将其内容修改为以下内容:

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "type": "shell",
            "command": "mkdir build ; cd build; cmake .. ; make",
            "group": "build",
            "presentation": {
                // Reveal the output only if unrecognized errors occur.
                "reveal": "silent"
            },
            // Use the standard MS compiler pattern to detect errors, warnings and infos
            "problemMatcher": "$msCompile"
        }
    ]
}

其中 label 的值一定要和 launch中的 preLaunchTask的值一样
修改 “command” 用于在调试之前先生成代码。
之后点击调试就可以自动进行调试了

参考自: https://code.visualstudio.com/docs/editor/debugging#_launch-configurations

猜你喜欢

转载自blog.csdn.net/m0_67391377/article/details/125345651