Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1522500
  • 博文数量: 290
  • 博客积分: 3468
  • 博客等级: 中校
  • 技术积分: 3461
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-28 22:21
文章分类

全部博文(290)

文章存档

2016年(13)

2015年(3)

2014年(42)

2013年(67)

2012年(90)

2011年(75)

分类: 嵌入式

2012-07-23 09:38:22

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




阅读(2814) | 评论(0) | 转发(2) |
给主人留下些什么吧!~~