注:原创不易,转载请务必注明原作者和出处,感谢支持!
一 写在开头
1.1 本文内容
总结GDB调试的一些常用命令和调试技巧。不定期更新。
二 学习资料
- The GNU Project Debugger
- 《软件调试的艺术》 (美)马特洛夫,(美)萨尔兹曼
三 常用命令
GDB的命令有很多,但只需要掌握下面常用的几个便可快速上手。
简写 | 全称 | 备注 |
---|---|---|
l | list | 显示指定行号或者指定函数附近的源代码 |
b | break | 在指定行号或者指定函数开头处设置断点。如b main |
r | run | 运行程序,直到程序结束或者遇到断点而停下 |
c | continue | 在程序中断后继续执行程序,直到程序结束或者遇到断点而停下。注意在程序开始执行前只能用r,不能用c |
n | next | 执行一条语句。如果有函数调用,则把它作为一个整体 |
s | step | 执行一条语句。如果有函数调用,则进入函数内部 |
u | until | 执行到指定行号或者指定函数的开头 |
p | 显示变量或表达式的值 | |
disp | display | 把一个表达式设置为display,当程序每次停下来时都会显示其值 |
cl | clear | 取消断点,和b的格式相同。如果该位置有多个断点,将同时取消 |
i | info | 显示各种信息。如i b显示所有断点,i disp显示display,而i lo显示所有局部变量 |
h | help | 获取帮助信息 |
四 调试技巧汇总
4.1 打印数组中的值
打印数组a的前6个值:p *a@6
打印数组a的第6个元素开始的后4个值:p *(a+5)@4
(gdb) l
1 #include <iostream>
2 using namespace std;
3
4 int main(int argc, char ** argv)
5 {
6 int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
7
8 cout << endl;
9 return 0;
10 }
(gdb)
11
(gdb) b 7
Breakpoint 1 at 0x40089a: file test.cpp, line 7.
(gdb) r
Starting program: /home/wallace/a.out
Breakpoint 1, main (argc=1, argv=0x7fffffffe528) at test.cpp:8
8 cout << endl;
(gdb) p *a@6
$1 = {0, 1, 2, 3, 4, 5}
(gdb) p *(a+5)@4
$2 = {5, 6, 7, 8}
(gdb)
4.2 同时打印多个变量的值
比如程序中有条输入语句为cin >> n >> m >> r >> c
,你想查看它们有没有正确被输入,你可以在这条语句之后同时打印它们的值。注意,同时打印的变量必须是同类型的。
(gdb) l 0
1 #include <iostream>
2 using namespace std;
3
4 int main(int argc, char ** argv)
5 {
6 int n, m, r, c;
7 n = m = r = c = 10;
8
9 return 0;
10 }
(gdb) b 8
Breakpoint 1 at 0x4006da: file test.cpp, line 8.
(gdb) r
Starting program: /home/wallace/a.out
Breakpoint 1, main (argc=1, argv=0x7fffffffe528) at test.cpp:9
9 return 0;
(gdb) p {n, m, r, c}
$1 = {10, 10, 10, 10}
(gdb)
4.3 查看断点并清除断点
使用info b
来查看所有的断点信息,使用del 断点号
命令来删除特定的一个断点,使用del 起始断点号-截止断点号
来删除多个断点。