GDB调试器

以该程序为例:

 1 /*test.c*/
 2 #include <stdio.h>
 3 int sum(int m);
 4 int main()
 5 {
 6         int i,n=0;
 7         sum(50);
 8         for(i=1; i<=50; i++)
 9         {
10                 n += i;
11         }
12         printf("The sum of 1-50 is %d \n", n );
13 }
14 int sum(int m)
15 {
16         int i,n=0;
17         for(i=1; i<=m;i++)
18                 n += i;
19         printf("The sum of 1-%d is %d\n",m, n);
20 }
使用Gcc对test.c进行编译,注意一定要加上选项“-g”,这样编译出的可执行代码中才包含调试信息,否则之后Gdb 无法载入该可执行文件。

[ht@localhost Test]$ gcc -g test.c -o test
[ht@localhost Test]$ ls
test  test.c
[ht@localhost Test]$ gdb test
GNU gdb (GDB) Fedora 7.8.1-30.fc21
Copyright (C) 2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i686-redhat-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from test...done.
(gdb)


1.查看文件
在 Gdb 中键入“l”(list)就可以查看所载入的文件。info b 可查询断点。

2.设置断点

只需在“b”后加入对应的行号即可。

(gdb) l
1    #include <stdio.h>
2    int sum(int m);
3    int main()
4    {
5        int i,n=0;
6            sum(50);
7        for(i=1; i<=50; i++)
8        {
9            n += i;
10        }
(gdb) b 6
Breakpoint 1 at 0x8048443: file test.c, line 6.
(gdb)
Gdb 中利用行号设置断点是指代码运行到对应行之前将其停止,如上例中,代码运行到第5行之前暂停(并没有运行第5 行)。

Gdb 中设置断点有多种方式:其一是按行设置断点,设置方法已经指出,另外还可以设置函数断点和条件断点。

函数断点:

(gdb) b sum
Breakpoint 2 at 0x804848a: file test.c, line 15.
(gdb)
条件断点:

(gdb) b 8 if i==10
Breakpoint 3 at 0x8048459: file test.c, line 8.
(gdb)

 

3.运行代码

Gdb默认从首行开始运行代码,可键入“r”(run)即可(若想从程序中指定行开始运行,可在r 后面加上行号)。

(gdb) r
Starting program: /home/ht/MYCODE/Test/test
Missing separate debuginfos, use: debuginfo-install glibc-2.20-5.fc21.i686

Breakpoint 1, main () at test.c:6
6            sum(50);
(gdb)

4.查看变量值

“p”+变量值即可。

(gdb) p n
$1 = 0

5.单步运行

使用命令“n”(next)或“s”(step),它们之间的区别在于:若有函数调用的时候,“s”会进入该函数而“n”不会进入该函数。

(gdb) n
The sum of 1-50 is 1275
7        for(i=1; i<=50; i++)
(gdb) s
9            n += i;
(gdb)

6.恢复程序运行

命令“c”(continue)恢复程序的正常运行。

 

7.修改运行时的参数

命令“set 变量=设定值”。

 

若用户已知命令名,直接键入“help [command]”查询。

 

 

posted @ 2015-02-27 17:04  ht-beyond  阅读(450)  评论(0编辑  收藏  举报