backtrace.c- #include <stdio.h>
- #include <stdlib.h>
- #include <execinfo.h>
- #define MAX_LEVEL 4
- void test2()
- {
- // printf("func:%s,line:%d\n",__FUNCTION__,__LINE__);
- int i = 0;
- void * buffer[MAX_LEVEL] = {0};
- int size = backtrace(buffer,MAX_LEVEL);
- for (i=0; i<size; i++){
- printf("called by %p\n",buffer[i]);
- }
- return ;
- }
- void test1()
- {
- // printf("func:%s,line:%d\n",__FUNCTION__,__LINE__);
- test2();
- }
- void test()
- {
- // printf("func:%s,line:%d\n",__FUNCTION__,__LINE__);
- test1();
- }
- int main(int argc,char *argv[])
- {
- test();
- return 0;
- }
编译:
# 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- #include <stdio.h>
- #include <stdlib.h>
- #include <execinfo.h>
- #define MAX_LEVEL 10
- void test2()
- {
- // printf("func:%s,line:%d\n",__FUNCTION__,__LINE__);
- int i = 0;
- void * buffer[MAX_LEVEL] = {0};
- int size = backtrace(buffer,MAX_LEVEL);
- for (i=0; i<size; i++){
- printf("called by %p\n",buffer[i]);
- }
- return ;
- }
- void test1()
- {
- // printf("func:%s,line:%d\n",__FUNCTION__,__LINE__);
- test2();
- }
- void test()
- {
- // printf("func:%s,line:%d\n",__FUNCTION__,__LINE__);
- test1();
- }
- int main(int argc,char *argv[])
- {
- test();
- return 0;
- }
编译:
# 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
阅读(6590) | 评论(0) | 转发(0) |