比如一个main.c 先通过运行命令 gcc -g main.c -o main 对main.c 进行编译,参数g的作用是把调试信息加入生成的main可执行文件中,否则GDB就无法对main进行测试。
接下来我将介绍一些基本的命令以及功能。命令功能 示例list (或缩写l)显示程序(以十行为单位进行显示) (gdb) lrun (r)运行程序(gdb) rbreak (b)设置断点(gdb) b 7 注:在第七行设置了第一个断点Info (i)查看断点情况(gdb) info b 查看断点情况print (p)查变量值(gdb) pnext (n)单步运行,不会进入子函数(gdb) nstep (s)单步运行,遇到函数时会进入子函数进一步执行(gdb) sdelete (d)删除断点(gdb) delete 1 注;删除第一个断点break函数名在调用到某一函数时停止(gdb) b maincontinue运行到下一断点结束,无断点则一运行(gdb) cfinish执行完当前函数返回到调用它的函数/进入单步执行若进入了某函数,而想退出该函数返回它的调用函数可用finish(gdb) finishquit (q)退出(gdb) q 接下来通过代码实现[root@localhost 00021]# gcc -g main.c -o main
[root@localhost 00021]# gdb main
GNU gdb Red Hat Linux (6.5-25.el5rh)
Copyright (C) 2006 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "i386-redhat-linux-gnu"...Using host libthread_db library "/lib/libthread_db.so.1". 先生成可执行文件main 再进入gdb调试(gdb) l
1 #include
2 int add_sum(int sum)
3 {
4 sum++;
5 return sum;
6 }
7 int main()
8 {
9 int i,sum=0;
10 for(i = 0;i <= 100;i++)
(gdb) l
11 {
12 sum = sum + i;
13 }
14 printf("%d
",add_sum(sum));
15 return 0;
16 }
17 (gdb) l 一次显示十行,没错,就是这样(gdb) b 14
Breakpoint 1 at 0x80483c1: file main.c, line 14.
(gdb) info b
Num Type Disp Enb Address What
1 breakpoint keep y 0x080483c1 in main at main.c:14
(gdb) run
Starting program: /root/0002/00021/main Breakpoint 1, main () at main.c:14
14 printf("%d
",add_sum(sum));
(gdb) s
add_sum (sum=5050) at main.c:4
4 sum++;
(gdb) finish
Run till exit from #0 add_sum (sum=5050) at main.c:4
0x080483cc in main () at main.c:14
14 printf("%d
",add_sum(sum));
Value returned is $1 = 5051
(gdb) s
5051
15 return 0; 先设置断点在14行, 然后run一下, 在断点处停下了,进行分布执行,可以看到在子函数里 sum++,通过finish 跳出子函数,继续单步执行 到最后了当然,中间想看变量值 可以再 print一下,大体上基本操作 就是表格里那些了,好了,是时候退出好好学习了