一,安裝GDB
[root@vmhostd ~]# rpm -q gdb
package gdb is not installed[root@vmhostd ~]# yum install gdb
.....
Installed:
gdb.i686 0:7.2-75.el6
Complete!
[root@vmhostd ~]# rpm -q gdb
gdb-7.2-75.el6.i686
[root@vmhostd ~]#
二,編寫編譯C程序
[root@vmhostd ~]# vi test.c
[root@vmhostd ~]# cat test.c
#include<stdio.h>
int add(int a, int b)
{
printf("a=%d,b=%d\n",a,b);
return a+b;
}
int main()
{
int a=1;
int b=2;
int res = add(a,b);
printf("res:%d\n",res);
}
[root@vmhostd ~]#
[root@vmhostd ~]# gcc test.c -o test -g
三,調試程序
[root@vmhostd ~]# gdb
GNU gdb (GDB) Red Hat Enterprise Linux (7.2-75.el6)
Copyright (C) 2010 Free Software Foundation, Inc.
...
<http://www.gnu.org/software/gdb/bugs/>.
(gdb) file test //加載程序文件
Reading symbols from /root/test...done.
(gdb) b add //設置斷點
Breakpoint 1 at 0x80483ca: file test.c, line 5.
(gdb) b main
Breakpoint 2 at 0x80483f9: file test.c, line 11.
(gdb) r //運行程序
Starting program: /root/test
Breakpoint 2, main () at test.c:11
11 int a=1;
Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.132.el6.i686
(gdb) p a //查看變量
$1 = 134513424
(gdb) s
12 int b=2;
(gdb) p a
$2 = 1
(gdb) c //繼續運行直至下一斷點
Continuing.
Breakpoint 1, add (a=1, b=2) at test.c:5
5 printf("a=%d,b=%d\n",a,b);
(gdb) p a
$3 = 1
(gdb) s //單步執行
a=1,b=2
6 return a+b;
(gdb) s
7 }
(gdb) s
main () at test.c:14
14 printf("res:%d\n",res);
(gdb) p res
$4 = 3
(gdb) c
Continuing.
res:3
Program exited normally.
(gdb)