分类:
用GDB调试程序
转自http://blog.csdn.net/haoel/article/details/2879
GDB概述
————
GDB是GNU开源组织发布的一个强大的UNIX下的程序调试工具。或许,各位比较喜欢那种图形界面方式的,像VC、BCB等IDE的调试,但如果你是在UNIX平台下做软件,你会发现GDB这个调试工具有比VC、BCB的图形化调试器更强大的功能。所谓“寸有所长,尺有所短”就是这个道理。
一般来说,GDB主要帮忙你完成下面四个方面的功能:
从上面看来,GDB和一般的调试工具没有什么两样,基本上也是完成这些功能,不过在细节上,你会发现GDB这个调试工具的强大,大家可能比较习惯了图形化的调试工具,但有时候,命令行的调试工具却有着图形化工具所不能完成的功能。让我们一一看来。
一个调试示例
——————
源程序:tst.c
编译生成执行文件:(Linux下)
使用GDB调试:
hchen/test> gdb tst
GNU gdb 5.1.1
Copyright 2002 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.
This GDB was configured as "i386-suse-linux"...
(gdb) l
1
2
3
4
5
6
7
8
9
10
(gdb)
11
12
13
14
15
16
17
18
19
20
(gdb) break 16
Breakpoint 1 at 0x8048496: file tst.c, line 16.
(gdb) break func
Breakpoint 2 at 0x8048456: file tst.c, line 5.
(gdb) info break
Num Type
1
2
(gdb) r
Starting program: /home/hchen/test/tst
Breakpoint 1, main () at tst.c:17
17
(gdb) n
18
(gdb) n
20
(gdb) n
18
(gdb) n
20
(gdb) c
Continuing.
result[1-100] = 5050
Breakpoint 2, func (n=250) at tst.c:5
5
(gdb) n
6
(gdb) p i
$1 = 134513808
(gdb) n
8
(gdb) n
6
(gdb) p sum
$2 = 1
(gdb) n
8
(gdb) p i
$3 = 2
(gdb) n
6
(gdb) p sum
$4 = 3
(gdb) bt
#0
#1
#2
(gdb) finish
Run till exit from #0
0x080484e4 in main () at tst.c:24
24
Value returned is $6 = 31375
(gdb) c
Continuing.
result[1-250] = 31375
Program exited with code 027. <--------程序退出,调试结束。
(gdb) q
hchen/test>
好了,有了以上的感性认识,还是让我们来系统地认识一下gdb吧。
使用GDB
————
一般来说GDB主要调试的是C/C++的程序。要调试C/C++的程序,首先在编译时,我们必须要把调试信息加到可执行文件中。使用编译器(cc/gcc/g++)的 -g 参数可以做到这一点。如:
如果没有-g,你将看不见程序的函数名、变量名,所代替的全是运行时的内存地址。当你用-g把调试信息加入之后,并成功编译目标代码以后,让我们来看看如何用gdb来调试他。
启动GDB的方法有以下几种:
GDB启动时,可以加上一些GDB的启动开关,详细的开关可以用gdb -help查看。我在下面只例举一些比较常用的参数: