下面按常见场景给你一套 Linux 下 C++ 调试配置方案,从「编译 → 调试器 → IDE/编辑器 → 常用技巧」循序渐进。
g++ -g -O0 main.cpp -o main
说明:
-g:生成调试符号(必须)-O0:关闭优化(否则变量可能被优化掉,断点不准)set(CMAKE_BUILD_TYPE Debug)
set(CMAKE_CXX_FLAGS_DEBUG "-g -O0")
或:
cmake -DCMAKE_BUILD_TYPE=Debug ..
gdb ./main
break main.cpp:10 # 断点
run # 运行
next # 单步(不进函数)
step # 单步(进函数)
print x # 打印变量
backtrace # 查看调用栈
continue # 继续运行
quit # 退出
ulimit -c unlimited
./main
gdb ./main core
.vscode/tasks.json(编译){
"version": "2.0.0",
"tasks": [
{
"label": "build",
"type": "shell",
"command": "g++ -g -O0 main.cpp -o main"
}
]
}
.vscode/launch.json(调试){
"version": "0.2.0",
"configurations": [
{
"name": "C++ Debug",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/main",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
无需手动配置 GDB
info threads
thread 2
run
bt
print vec
(GDB 新版本支持较好)
#include <iostream>
#define LOG(x) std::cout << #x << " = " << x << std::endl;
或:
strace ./main
❌ 断点不生效
✅ 忘了 -g 或开了 -O2
❌ 变量显示 <optimized out>
✅ 使用 -O0
❌ GDB 看不懂 C++ 名字
✅ 使用 g++ 而非 gcc
如果你愿意,可以告诉我:
我可以直接给你对应配置模板。