推荐我的个人博客 blog.wuzhenyu.com.cn
gdb 调试总结
编译程序
当编译程序,使用 gcc/g++ (the GNU c/c++ compiler) 作为编译器时,为了产生调试信息,可以使用 ‘-g’ 的调试选项。老版本的编译器可能会支持 ‘-gg’ 的调试选项,但是这种已经被淘汰,即使你现在使用的编译器版本仍然支持这种编译选项,也不要使用。调试信息都保存在目标文件中。
Specify ‘-g’ option when you run the complier, to generate the debugging information for your program. This debugging information is stored in the object file; it describes the data type of each variable and function and the correspondence between source line numbers and addresses in excutable code.
支持对宏的处理
GDB 能够识别预编译宏定义,并且能够对其展开(show preprocessor macros’ expansion)。3.1 版本以后的 GCC 编译器,使用 ‘-g3’ 编译选项和 DWARF 调试格式的情况下,能够提供宏信息。
GDB 能够对含有宏调用的表达式进行求值,能够显示宏展开的结果,能够显示宏定义,包括宏定义的地方。
GDB can evaluate expressions containing
macro invocations, show the result of macro expansion, and show a macro’s definition, including where it was defined.
gdb 的宏操作
1、
macro expand expression
macro exp expression
对宏表达式进行展开
2、
info macro macroname
显示宏定义,能够显示宏定义的具体位置,比如在源文件的某一行,被哪个文件的哪一行所引用
比如
#include <stdio.h>
#include "sample.h"
#define M 42
#define ADD(x) (M + x)
main ()
{
#define N 28
printf ("Hello, world!\n");
#undef N
printf ("We’re so creative.\n");
#define N 1729
printf ("Goodbye, world!\n");
}
编译
gcc -DWARF -g3 sample.c
使用 gdb 进入调试
(gdb) info macro ADD
Defined at /home/jimb/gdb/macros/play/sample.c:5
#define ADD(x) (M + x)
(gdb) macro expand ADD(1)
expands to: (42 + 1)
info macro 能够显示宏定义的具体位置,但是有一些是在编译中使用 -Dname=value
的形式,来添加宏的,这种宏,GDB在显示它们的位置的时候,显示的源文件的第 0 行,如下所示
(gdb) info macro __STDC__
Defined at /home/jimb/gdb/macros/play/sample.c:0
-D__STDC__=1
注意,一般现在版本的 GCC 编译器,可能支持 -gdwarf2 -gdwarf3 -gdwarf4 这几种编译选项,一般推荐使用最新版本的 -DWARF
启动程序
进入gdb调试,输入 run 或者 r 运行程序。
设置参数
set args 设置程序运行时的命令行参数,比如
(gdb) set args a b