backtrace 和 backtrace_symbols 打印函数调用关系

backtrace.c

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <execinfo.h>

  4. #define MAX_LEVEL 4

  5. void test2()
  6. {
  7. //    printf("func:%s,line:%d\n",__FUNCTION__,__LINE__);

  8.     int i = 0;
  9.     void * buffer[MAX_LEVEL] = {0};

  10.     int size = backtrace(buffer,MAX_LEVEL);

  11.     for (i=0; i<size; i++){
  12.         printf("called by %p\n",buffer[i]);
  13.     }

  14.     return ;
  15. }

  16. void test1()
  17. {
  18. //    printf("func:%s,line:%d\n",__FUNCTION__,__LINE__);
  19.     test2();
  20. }

  21. void test()
  22. {
  23. //    printf("func:%s,line:%d\n",__FUNCTION__,__LINE__);
  24.     test1();
  25. }

  26. int main(int argc,char *argv[])
  27. {
  28.     test();

  29.     return 0;
  30. }
编译:
# gcc -g backtrace.c 
#  ./a.out | awk '{print "addr2line "$3" -e a.out"}' > t.sh
# . t.sh
/home/step_by_step/c_c++/backtrace/backtrace.c:14
/home/step_by_step/c_c++/backtrace/backtrace.c:27
/home/step_by_step/c_c++/backtrace/backtrace.c:33
/home/step_by_step/c_c++/backtrace/backtrace.c:39

备注:
若编译时没有加 -g 参数没有调试信息 获得的结果是
??:0
??:0
??:0
??:0



点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <execinfo.h>

  4. #define MAX_LEVEL 10

  5. void test2()
  6. {
  7. //    printf("func:%s,line:%d\n",__FUNCTION__,__LINE__);

  8.     int i = 0;
  9.     void * buffer[MAX_LEVEL] = {0};

  10.     int size = backtrace(buffer,MAX_LEVEL);

  11.     for (i=0; i<size; i++){
  12.         printf("called by %p\n",buffer[i]);
  13.     }

  14.     return ;
  15. }

  16. void test1()
  17. {
  18. //    printf("func:%s,line:%d\n",__FUNCTION__,__LINE__);
  19.     test2();
  20. }

  21. void test()
  22. {
  23. //    printf("func:%s,line:%d\n",__FUNCTION__,__LINE__);
  24.     test1();
  25. }

  26. int main(int argc,char *argv[])
  27. {
  28.     test();

  29.     return 0;
  30. }
编译:
# gcc -g -rdynamic backtrace.c 
# ./a.out
called by 0x8048710 -- ./a.out(
test2 +0x3c) [0x8048710]
called by 0x8048772 -- ./a.out(
test1 +0xb) [0x8048772]
called by 0x804877f -- ./a.out(
test +0xb) [0x804877f]
called by 0x804878c -- ./a.out(
main +0xb) [0x804878c]
called by 0xbc7bd6 -- /lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe6) [0xbc7bd6]
called by 0x8048641 -- ./a.out() [0x8048641]

出现函数名了和地址,行号则可以通过 addr2line 工具把地址转换就好了
# addr2line -e a.out 0x8048710
/home/step_by_step/c_c++/backtrace/backtrace.c:14

参考:
http://blog.csdn.net/wind19/article/details/6105617
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值