0.GDB 环境准备指南
0.1 GDB 安装
1. Linux 系统
大多数 Linux 发行版都可以通过包管理器直接安装:
- Ubuntu/Debian 系列:
sudo apt update
sudo apt install gdb -y
- Fedora/RHEL 系列:
sudo dnf install gdb -y # 或者使用 yum install gdb
- Arch Linux:
sudo pacman -S gdb
安装完成后,可通过以下命令确认版本:
gdb --version
2. Windows 系统
Windows 用户可以通过 MinGW-w64 或 MSYS2 安装 GDB:
-
MinGW-w64:
- 下载并安装 MinGW-w64(官网)。
- 在安装选项中确保选择
mingw32-gdb。 - 添加 GDB 所在路径到系统
PATH。
-
MSYS2:
pacman -Syu
pacman -S mingw-w64-x86_64-gdb
3. macOS 系统
macOS 用户可以通过 Homebrew 安装:
brew install gdb
注意:macOS 上使用 GDB 时,需要对 GDB 签名,否则调试权限会被限制。可通过
codesign创建签名证书并签署 gdb。
0.2 编译选项准备
GDB 只能调试带 调试信息 的程序。建议使用 -g 编译选项,同时禁用优化以便调试:
g++ -g -O0 main.cpp -o main
说明:
-g:生成调试信息。-O0:关闭优化,避免编译器重排影响调试。-Wall(可选):开启所有警告,帮助发现潜在问题。
0.3 GDB 基础配置
0.3.1. 启动 GDB
gdb ./main
进入 GDB 后,可以使用以下命令:
(gdb) break main # 设置断点
(gdb) run # 启动程序
(gdb) next # 单步执行(跳过函数)
(gdb) step # 单步执行(进入函数)
(gdb) print var # 打印变量值
(gdb) continue # 继续执行到下一个断点
(gdb) quit # 退出 GDB
0.3.2. 设置 GDB 配置文件
可以在 ~/.gdbinit 文件中添加常用配置,例如:
# 显示代码行号
set listsize 20
# 显示十六进制变量
set output-radix 16
# 自动加载 Python 脚本或 pretty printer
python
import sys
sys.path.insert(0, '/path/to/pretty_printer')
end
.gdbinit可以帮助你在每次启动 GDB 时自动加载常用设置,提高调试效率。
0.4 结合 VSCode / CLion 使用 GDB
现代 IDE 可以把 GDB 嵌入调试界面,使调试更加可视化:
-
VSCode:
- 安装 C/C++ 插件(Microsoft 提供)。
- 配置
launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug C++",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/main",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
]
}
-
CLion:
- CLion 自带 GDB 支持。
- 在 Settings → Build, Execution, Deployment → Toolchains 中配置 GDB 路径。
- 在 Debug 配置中直接选择可执行程序即可。
0.5 扩展工具
- GDB Dashboard:命令行增强界面,显示寄存器、堆栈和变量。
git clone https://github.com/cyrus-and/gdb-dashboard.git ~/.gdb-dashboard
echo "source ~/.gdb-dashboard/.gdbinit" >> ~/.gdbinit
-
Python Pretty Printer:打印 STL 容器更友好。
- 常见库:libstdc++-v6 pretty printers
- 自动加载可在
.gdbinit中配置。
0.6 常见问题
- 程序无法断点:确认编译带
-g,并关闭优化-O0。 - 变量显示为
<optimized out>:说明编译器优化掉了变量,需要关闭优化。 - GDB 启动报错权限(macOS):执行签名操作:
codesign -s gdb-cert /usr/local/bin/gdb

浙公网安备 33010602011771号