VSCode C++ 调试方法

VSCode 调试 C++ 主要就是 .vscode 中的 launch.json 和 tasks.json 的配置。

launch.json 可以通过 vscode 界面 ------》左侧调试功能按钮------》创建 launch.json ------》C++(GDB/LLDB)生成。

其中 launch.json 默认配置如下,主要配置项说明:

  • name:启动项的名字

  • program:指向最终生成的可执行文件的路径

  • args:执行时的输入参数

  • stopAtEntry:自动在 main 函数时停止

    {
    "version": "0.2.0",
    "configurations": [
    {
    "name": "C/C++: g++ build and debug active file",
    "type": "cppdbg",
    "request": "launch",
    "program": "{fileDirname}/{fileBasenameNoExtension}",
    "args": [],
    "stopAtEntry": false,
    "cwd": "${workspaceFolder}",
    "environment": [],
    "externalConsole": false,
    "MIMode": "gdb",
    "miDebuggerPath": "/usr/bin/gdb",
    "setupCommands": [
    {
    "description": "Enable pretty-printing for gdb",
    "text": "-enable-pretty-printing",
    "ignoreFailures": true
    }
    ],
    "preLaunchTask": "C/C++: g++ build active file"
    }
    ]
    }

tasks.json 文件可以通过 vscode 菜单 ------》终端------》配置任务 生成。

其中 tasks.json 默认配置如下,主要配置项说明:

  • command:给出具体编译命令,可以是 /usr/bin/g++,也可以是基于 CMakeLists.txt 直接输入 cmake 命令

  • args:编译命令输入参数

  • group.isDefault:是否为默认编译方式,True 表示默认使用此编译选项

    {
    "version": "2.0.0",
    "tasks": [
    {
    "type": "shell",
    "label": "C/C++: g++ build active file",
    "command": "/usr/bin/g++",
    "args": ["-g", "{file}", "-o", "{fileDirname}/{fileBasenameNoExtension}"], "options": { "cwd": "/usr/bin" }, "problemMatcher": ["gcc"],
    "group": {
    "kind": "build",
    "isDefault": true
    },
    "detail": "Task generated by Debugger."
    }
    ]
    }

CMakeLists.txt 方式

如果使用 CMakeLists.txt,需要在 CMakeLists.txt 中添加如下行,从而以 Debug 方式(一共有以下方式:Debug Release RelWithDebInfo 和 MinSizeRel)编译。

复制代码
SET(CMAKE_BUILD_TYPE "Debug") 
SET(CMAKE_CXX_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g -ggdb")
SET(CMAKE_CXX_FLAGS_RELEASE "$ENV{CXXFLAGS} -O3 -Wall")

tasks.json 配置中对应 command 修改如下

复制代码
{
	"version": "2.0.0",
	"tasks": [
        {
            ...
            "command": "cmake . -B build -DCMAKE_BUILD_TYPE=Debug;cmake --build build --target main --config Debug -j",
            "args": [],
            ...
    ]
}
相关推荐
h39742 小时前
DirectShow过滤器开发-视频源过滤器
c++·windows·音视频·directshow
程序猿编码4 小时前
榨干 RTX5090 算力!Qwen3 专用单卡推理引擎,手写C++/CUDA 算子实现 MTP 推测解码
开发语言·c++·大模型推理·qwen3·多模态推理
西飘客5 小时前
vs 怎么根据dll 生成lib文件
c++·qt
程序员老陆6 小时前
深入理解 C++ thread_local:线程私有存储的正确打开方式
开发语言·c++·程序设计
半杯咖啡半行码9 小时前
C++ 编程与 STL 模板:从泛型编程到内存安全详解
开发语言·c++
kite012110 小时前
TraeCode 与 TraeWork 合并:AI 时代 IDE 的三种形态与未来开发工具
ide·ade·traework·traecode
xh didida10 小时前
Linux -- 基础IO
linux·服务器·开发语言·c++
weixin_4617694010 小时前
VS Code 中创建 Jupyter 文件(.ipynb)
ide·python·jupyter
垆边人似月.10 小时前
华为机试题 :两数之和
c++·算法·华为
个 人 练 习 生10 小时前
C++ string 类模拟实现:从底层理解字符串(上)
开发语言·c++·经验分享·学习·程序人生