gcc compiling for debugging

正常情况下因为可执行文件并不包含源代码的信息,如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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值