GDB调试器

GDB是GUN开发的一款强大的程序调试工具

gdb的缺点是没有图形调试界面,但尽管如此,对于从事linux应用开发的人员还是有必要知道gdb的使用方法的

首先,我先说一下gdb的三大功能:

1.gdb能启动被调试程序

2.让被调试的程序在指定位置上停止

3.可以在指定位置上面测出状态值


首先,先了解一下gdb的一些基本指令

1.查看源文件  l(list的缩写)

2.设置断点    b(break的缩写)

3.查看断点情况  info b

4.运行程序   r(run的缩写)

5.查看变量值  p(printf的缩写)

6.继续运行程序 c(continue的缩写)

7.单步运行   s\n  (step\next的缩写)

8.退出gdb  quit


下面让我以test.c为例,讲一下gdb的一些基本用法

1       #include <stdio.h>

2       int cal(int n)

3       {
4           if(n == 1)
5               return 1;
6           else
7               return n * cal(n - 1);
8       }
9
10      int main()
11      {
12          int n = 5;
13          n = cal(5);
14          printf("%d", n);
15          return 0;
16      }


在运行gdb之前,我们要知道gdb不能直接对程序进行操作,我们要用到命令 -g,其中参数-g的作用是将调试信息封装到可执行文件中,

如本题就应该先通过运行命令gcc-g -test.c -o test,生成test可执行文件,然后通过gdb test来启动gdb进行调试


[root@localhost GDB]# gdb test
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.

然后进行调试

1.查看源文件  l,其中gdb是以10行单位进行显示

(gdb) l
3       {
4           if(n == 1)
5               return 1;
6           else
7               return n * cal(n - 1);
8       }
9
10      int main()
11      {
12          int n = 5;
(gdb) 
13          n = cal(5);
14          printf("%d", n);
15          return 0;
16      }
(gdb) 


2.设置断点 b

(gdb) b 7
Breakpoint 1 at 0x8048399: file test.c, line 7.

命令b在第7行设置了第一个断点,并显示该断点在内存中的物理地址


3.查看断点情况 info b

(gdb) info b
Num Type           Disp Enb Address    What
1   breakpoint     keep y   0x08048399 in cal at test.c:7

可以看到在第7行设置了第一个断点,并显示了断点的 位置信息


4.运行程序 r

(gdb) r
Starting program: /root/0709/GDB/test 


Breakpoint 1, cal (n=5) at test.c:7
7               return n * cal(n - 1);

可以看到,程序在第7 行就停止了,没有继续运行第8行的程序


5.查看变量值  p

(gdb) p n
$1 = 5

gdb通过“SN”来显示变量的值,这样下次查看变量值得时候就可以用“SN”代替变量值了


6.继续运行程序 c

Continuing.

Breakpoint 1, cal (n=4) at test.c:7
7               return n * cal(n - 1);

在程序暂停后再次查看当前变量的值,如下所示

(gdb) p n
$2 = 4


7.单步执行 s\n

s与n都可以让程序一步步运行下去,但s可以在发生函数调用时进入函数内部运行,而n不会进入函数内部运行

(gdb) s
cal (n=3) at test.c:4
4           if(n == 1)
(gdb) s

Breakpoint 1, cal (n=3) at test.c:7
7               return n * cal(n - 1);
(gdb) 


8.退出gdb  quit

(gdb) quit
The program is running.  Exit anyway? (y or n) y

此外,gdb还有许多功能,如使用shell命令等,在此就不深入介绍了,我会在以后的学习中继续完善,有兴趣的读者可以自行参考相关资料



















  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值