gdb 基本用法

What is gdb?

gdbGNU Debugger 的缩写,用来调试程序,支持的语言有[1]:

  • Ada
  • C
  • C++
  • Objective-C
  • Free Pascal
  • Fortran
  • Java

小试牛刀

写一个简单的小程序,然后用 gdb 调试一下。

1
2
3
4
5
6
7
8
9
#include <stdio.h>
int main(void)
{
int i;
scanf("%d, &i);
printf("i = %d\n", i);
return 0;
}

编译:

1
$ gcc main.c -std=C99

为了方便 gdb 调试,窝们加一个 -g 参数。

1
$ gcc main.c -g -std=C99

不出问题的话应该会有一个 a.out 文件。
窝们用 gdb 调试它:

1
$ gdb a.out

不出问题的话应该可以看到一个这样的界面:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.04) 7.11.1
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from a.out...(no debugging symbols found)...done.
(gdb)

(gdb) 就是 gdb 的提示符,类似 Unix$#

1
(gdb) break 9

在 9 行中下一个断点,把程序跑起来:

1
(gdb) run

不出问题的话程序应该断在了第9行,然后输入 233,回车。
现在的话是断在第9(10)行了。窝们可以去看一下它的变量之类的操作:

1
(gdb) print i

返回结果:

1
2
3
(gdb) print i
$1 = 233
(gdb)

还可以修改 i 的值:

1
(gdb) set i = 233333

想要退出 gdb 的话可以用 quit 命令。

Next 和 Step 指令

next 指令会步过,但是不会跟踪函数(步入),而 step 会步入函数。

参考

1 GDB Documentation - Supported Languages.