本案例总结了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 <stdio.h>
#include <stdlib.h>
#include <string.h>
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 start\n");
int ret = -1;
struct GDB_TEST *test = &my_dgb_test;
if (test->gdb_int == 0)
{
ret = 0;
printf("now ret and gdb_int is 0\n");
}
if (test->gdb_int == 1)
{
ret = 1;
printf("now ret and gdb_int is 1\n");
}
printf("return\n");
return;
}
实践:
/* step1: 使用-g选项编译二进制可执行程序 */
[10283203@zte.intra@127 c_code]$ gcc -g gdb_test.c -o gdb_test
/* step2: gdb 文件名 开始gdb调试 */
[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.
/* step3:设置断点 */
(gdb) b main
Breakpoint 1 at 0x40058e: file gdb_test.c, line 21.
/* step4:开始运行*/
(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 start\n");
/* 单步执行 */
(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)
/* step5:print命令查看变量值 */
(gdb) print test->gdb_int
$1 = 5
/* step6:set命令修改变量值,单步执行,通过打印确定修改成功 */
(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 0\n");
(gdb) n
now ret and gdb_int is 0
/* step6:set命令修改变量值,单步执行,通过打印确定修改成功 */
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 1\n");
/* 执行到程序结束 */
(gdb) c
Continuing.
now ret and gdb_int is 1
return
[Inferior 1 (process 1297) exited with code 07]
(gdb) quit
|