- GNU 调试器有用资源
- GDB - 快速指南
- GDB - 资源
GDB - 调试示例 1
让我们编写一个程序以生成核心转储。
#include <iostream>
using namespace std;
int divint(int, int);
int main()
{
int x = 5, y = 2;
cout << divint(x, y);
x =3; y = 0;
cout << divint(x, y);
return 0;
}
int divint(int a, int b)
{
return a / b;
}
为了启用调试,必须使用 -g 选项来编译该程序。
$g++ -g crash.cc -o crash
注意:我们使用 g++ 编译器,因为我们使用了 C++ 源代码。
现在,当您在您的 linux 设备上运行此程序时,它将生成以下结果
Floating point exception (core dumped)
您将在您的当前目录中找到一个 core 文件。
现在,要调试问题,请在命令提示符下启动 gdb 调试器
$gdb crash # Gdb prints summary information and then the (gdb) prompt (gdb) r Program received signal SIGFPE, Arithmetic exception. 0x08048681 in divint(int, int) (a=3, b=0) at crash.cc:21 21 return a / b; # 'r' runs the program inside the debugger # In this case the program crashed and gdb prints out some # relevant information. In particular, it crashed trying # to execute line 21 of crash.cc. The function parameters # 'a' and 'b' had values 3 and 0 respectively. (gdb) l # l is short for 'list'. Useful for seeing the context of # the crash, lists code lines near around 21 of crash.cc (gdb) where #0 0x08048681 in divint(int, int) (a=3, b=0) at crash.cc:21 #1 0x08048654 in main () at crash.cc:13 # Equivalent to 'bt' or backtrace. Produces what is known # as a 'stack trace'. Read this as follows: The crash occurred # in the function divint at line 21 of crash.cc. This, in turn, # was called from the function main at line 13 of crash.cc (gdb) up # Move from the default level '0' of the stack trace up one level # to level 1. (gdb) list # list now lists the code lines near line 13 of crash.cc (gdb) p x # print the value of the local (to main) variable x
在这个示例中,很明显崩溃是因为尝试将一个整数除以 0。
要调试一个已崩溃并生成了名为“core”的核心文件的程序“crash”,请在命令行键入以下内容
gdb crash core
由于这基本上相当于启动 gdb 并键入“r”命令,因此现在可以使用上述所有命令来调试该文件。
gdb_debugging_examples.htm
广告