本案例总结了gdb的常用用法,详细规则可参考gdb入门教程
总结在前:
- 编译命令gcc -g gdb_test.c -o gdb_test,通过-g选项添加调试信息,否则使用gdb调试时,会报“No symbol table is loaded. Use the "file" command.”错误。
- 设置断点:bread(或b) 函数名; bread(或b) -line 行号;例如b main 或 b -line 21。
- 开始运行:run,该命令会直接运行到断点位置或直至结束。
- 单步执行:next(n),该命令将程序执行一行。
- 打印变量:print 变量名,例如print ret。
- 修改变量:set 变量名=变量值,例如set ret=1。
- 多步执行:continue©,继续运行您的程序 (在停止之后,比如在一个断点之后)。
源代码如下:
#include#include #include struct GDB_TEST { int gdb_int; char gdb_char[64]; }; static struct GDB_TEST my_dgb_test = { .gdb_int = 5, .gdb_char = "This is my test", }; void main() { printf("main startn"); int ret = -1; struct GDB_TEST *test = &my_dgb_test; if (test->gdb_int == 0) { ret = 0; printf("now ret and gdb_int is 0n"); } if (test->gdb_int == 1) { ret = 1; printf("now ret and gdb_int is 1n"); } printf("returnn"); return; }
实践:
[10283203@zte.intra@127 c_code]$ gcc -g gdb_test.c -o gdb_test
[10283203@zte.intra@127 c_code]$ gdb gdb_test
GNU gdb (GDB) Red Hat Enterprise Linux 8.2-6.el8
……省略gdb版本信息……
Reading symbols from gdb_test...done.
(gdb) b main
Breakpoint 1 at 0x40058e: file gdb_test.c, line 21.
(gdb) run
Starting program: /media/vdb1/code_test/c_code/gdb_test
Missing separate debuginfos, use: yum debuginfo-install glibc-2.28-72.el8_1.1.x86_64
Breakpoint 1, main () at gdb_test.c:21
21 printf("main startn");
(gdb) n
main start
22 int ret = -1;
(gdb) n
23 struct GDB_TEST *test = &my_dgb_test;
(gdb)
25 if (test->gdb_int == 0)
(gdb) print test->gdb_int
$1 = 5
(gdb) set test->gdb_int=0
(gdb) print test->gdb_int
$2 = 0
(gdb) n
27 ret = 0;
(gdb) n
28 printf("now ret and gdb_int is 0n");
(gdb) n
now ret and gdb_int is 0
31 if (test->gdb_int == 1)
(gdb) print test->gdb_int
$3 = 0
(gdb) set test->gdb_int=1
(gdb) print test->gdb_int
$4 = 1
(gdb) n
33 ret = 1;
(gdb)
34 printf("now ret and gdb_int is 1n");
(gdb) c
Continuing.
now ret and gdb_int is 1
return
[Inferior 1 (process 1297) exited with code 07]
(gdb) quit



