2024年6月2日发(作者:)

1、GDB 启动

一般来说GDB主要调试的是C/C++的程序。要调试C/C++的程序,首先在编译时,

我们必须要把调试信息加到可执行文件

中。使用编译器(cc/gcc/g++)的 -g 参数可以做到这一点。如:

> cc -g hello.c -o hello

> g++ -g -o hello

如果没有-g,你将看不见程序的函数名、变量名,所代替的全是运行时的内存地

址。当你用-g把调试信息加入之后,并

成功编译目标代码以后,让我们来看看如何用gdb来调试他。

启动GDB的方法有以下几种:

1、gdb

program也就是你的执行文件,一般在当然目录下。

2、gdb core

用gdb同时调试一个运行程序和core文件,core是程序非法执行后core dump后产

生的文件。

3、gdb

如果你的程序是一个服务程序,那么你可以指定这个服务程序运行时的进程ID。

gdb会自动attach上去,并调试他。

program应该在PATH环境变量中搜索得到。

GDB启动时,可以加上一些GDB的启动开关,详细的开关可以用gdb -help查看。

我在下面只例举一些比较常用的参数:

-symbols

-s

从指定文件中读取符号表。

-se file

从指定文件中读取符号表信息,并把他用在可执行文件中。

-core

-c

调试时core dump的core文件。

-directory

-d

加入一个源文件的搜索路径。默认搜索路径是环境变量中PATH所定义的路径。

2、GDB的命令概貌

启动gdb后,就你被带入gdb的调试环境中,就可以使用gdb的命令开始调试程序了,gdb

的命令可以使用help命令来查看,如下所示:

/home/hchen> gdb

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. Type "show warranty" for details.

This GDB was configured as "i386-suse-linux".

(gdb) help

List of classes of commands:

aliases -- Aliases of other commands

breakpoints -- Making program stop at certain points

data -- Examining data

files -- Specifying and examining files

internals -- Maintenance commands

obscure -- Obscure features

running -- Running the program

stack -- Examining the stack

status -- Status inquiries

support -- Support facilities

tracepoints -- Tracing of program execution without stopping the program

user-defined -- User-defined commands

Type "help" followed by a class name for a list of commands in that class.

Type "help" followed by command name for full documentation.

Command name abbreviations are allowed if unambiguous.

(gdb)

gdb的命令很多,gdb把之分成许多个种类。help命令只是例出gdb的命令种类,如果要看

种类中的命令,可以使用help 命令,如:help breakpoints,查看设置断点的所有命令。也

可以直接help 来查看命令的帮助。

gdb中,输入命令时,可以不用打全命令,只用打命令的前几个字符就可以了,当然,命令

的前几个字符应该要标志着一个唯一的命令,在Linux下,你可以敲击两次TAB键来补齐

命令的全称,如果有重复的,那么gdb会把其例出来。

示例一:在进入函数func时,设置一个断点。可以敲入break func,或是直接就是b func

(gdb) b func

Breakpoint 1 at 0x8048458: file hello.c, line 10.

示例二:敲入b按两次TAB键,你会看到所有b打头的命令:

(gdb) b

backtrace break bt

(gdb)

示例三:只记得函数的前缀,可以这样: