在需要gdb对程序进行调试时,首先,我们需要在编译时将调试信息加入到可执行文件中。我们可以使用编译器中的-g
参数来实现。
如:
gcc -g hello.c -o hello
g++ -g hello.cpp -o hello
如果没有加入调试信息,将看不到程序的函数名、变量名,所代替的全是运行时的
我们可以通过gdb <program> program
来启动gdb,program是可执行文件(注:一般是加了调试信息的可执行文件 =>即编译时加了-g参数编译的)
同时,gdb可以同时调试一个运行的程序和core文件,其中,core是非法执行后core dump后产生的文件
gdb <program> core
gdb还可以调试一个服务程序,如果是一个服务程序,我们可以指定服务程序运行时的进程ID,gdb会自动的attach上去,并调试它。
gdb <program> <PID>
在启动gdb时,我们可以使用参数,对于具体的参数,我们可以在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)
键入“help”,后跟一个类名,表示该类中的命令列表。
如:help data
键入“help”,然后键入命令名,以获得完整的文档。
如果没有歧义,则允许使用命令名缩写。(gdb)
如:help print