程序的发布方式有两种,debug模式和release模式
Linux gcc/g++出来的二进制程序,默认是release模式
要使用gdb调试,必须在源代码生成二进制程序的时候, 加上 -g 选项,生成debug模式的程序
对源文件编译的时候加上-g选项,否则会提示没有调试符号
下面是对于debug版本程序的调试
注意:gdb会记录最近一条命令,如果命令无变化,可以直接回车
- (gdb) l 0
- 1 #include
- 2
- 3 int AddToTop(int top)
- 4 {
- 5 int sum = 0;
- 6 int i = 0;
- 7 for (i = 0; i < top; i++)
- 8 {
- 9 sum += i;
- 10 }
- (gdb)
- 11 return sum;
- 12 }
- 13
- 14 int main()
- 15 {
- 16 int top = 100;
- 17
- 18 int ret = AddToTop(top);
- 19
- 20 printf("ret:%d\n", ret);
- (gdb)
- 21
- 22 return 0;
- 23 }
- (gdb)
- Line number 24 out of range; test.c has 23 lines.
指令l 0意为从代码第一行开始显示
如果没有遇到断点就直接运行结束,并且每次都从最开始运行程序
- (gdb) l 0
- 1 #include
- 2
- 3 int AddToTop(int top)
- 4 {
- 5 int sum = 0;
- 6 int i = 0;
- 7 for (i = 0; i < top; i++)
- 8 {
- 9 sum += i;
- 10 }
- (gdb)
- 11 return sum;
- 12 }
- 13
- 14 int main()
- 15 {
- 16 int top = 100;
- 17
- 18 int ret = AddToTop(top);
- 19
- 20 printf("ret:%d\n", ret);
- (gdb)
- 21
- 22 return 0;
- 23 }
- (gdb) b 16
- Breakpoint 1 at 0x40056a: file test.c, line 16.
- (gdb) b 18
- Breakpoint 2 at 0x400571: file test.c, line 18.
- (gdb) b 20
- Breakpoint 3 at 0x40057e: file test.c, line 20.
- (gdb) info b
- Num Type Disp Enb Address What
- 1 breakpoint keep y 0x000000000040056a in main at test.c:16
- 2 breakpoint keep y 0x0000000000400571 in main at test.c:18
- 3 breakpoint keep y 0x000000000040057e in main at test.c:20
Num表示的是断点的编号
- (gdb) d 1
- (gdb) d 2
- (gdb) d 3
- (gdb) info b
- No breakpoints or watchpoints.
需要先打一个断点然后用r进入到调试模式
要确保变量没有被销毁才能打印出来
- (gdb) p ret
- $5 = 4950
- (gdb) bt
- #0 AddToTop (top=100) at test.c:7
- #1 0x000000000040057b in main () at test.c:18
- (gdb) finish
- Run till exit from #0 AddToTop (top=100) at test.c:7
- 0x000000000040057b in main () at test.c:18
- 18 int ret = AddToTop(top);
每调试一步都会将设置了常显示的变量的值给显示出来
- (gdb) undisplay
- Delete all auto-display expressions? (y or n) y
(gdb) disable 2
- (gdb) set var top
- warning: Expression is not an assignment (and might have no effect)
- (gdb) set var top=80
- (gdb) p top
- $3 = 80