您的位置:首页 > 其它

gcc compiling for debugging

2013-11-08 20:33 148 查看
正常情况下因为可执行文件并不包含源代码的信息,如variable names line number,这对于debug过程是远远不够的,因为一旦程序崩溃,我们便无能为力。

为此gcc 提供了 -g debug option来将dubugging information 保存在目标文件和可执行文件中,这些信息可以使用debugger如 gdb工具来进行debug过程。使用debugger也可以在程序运行的时候观察变量的值。

当程序非正常退出时候,操作系统会生成一个core文件,该文件包含了( the in-memory state of the program at the time it crashed),加上-g生成的信息,就可以开启debug过程。

如以下程序

#include<stdio.h>

int a(int* pointer);

int main()
{
int* p  = 0;

return a(p);
}

int a(int* pointer)
{
int y = *pointer;
return y;
}

// gcc -Wall -g test.c -o a

// ./a

会出现 Segmentation fault(core dumped),当出现core dumped时候,系统就应该在当前目录产生一个core文件(奇怪了,试了几次我没有出现呢我是64位ubuntu 12.04,或者是产生了core 但放在了别处???待解)在bash里面键入ulimit -c 如果是0 的话是不会产生的,可以使用ulimit -c unlimited来修改这个值,这种修改仅对当前的shell有用(.bash_profile)

然后键入 gdb a core , 此处a即为上述生成的可执行文件,core为相对应的core文件,两者缺一不可,之后会提示如下信息

GNU gdb (Ubuntu/Linaro 7.4-2012.02-0ubuntu2) 7.4-2012.02
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
For bug reporting instructions, please see:
<http://bugs.launchpad.net/gdb-linaro/>...
Reading symbols from /home/sharp/Desktop/b...done.
[New LWP 6371]

warning: Can't read pathname for load map: Input/output error.
Core was generated by `./b'.
Program terminated with signal 11, Segmentation fault.
#0  0x00000000004004de in a (pointer=0x0) at test.c:14
14		int y = *pointer;
(gdb)


然后可以 在gdb中使用print什么的来debug

当然,也可以在gdb中使用backtrace来show function calls and arguments,方法是只用在gdb条件下键入backtrace 即可,更多资料参阅 debugging with gdb
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: