https://man7.org/linux/man-pages/man3/backtrace.3.html
1 #include <stdio.h> 2 #include <string.h> 3 #include <stdint.h> 4 #include <stdlib.h> 5 #include "execinfo.h" 6 7 typedef uint32_t UINT32; 8 9 void fun3(void) 10 { 11 void* array[10] = {0}; 12 UINT32 size = 0; 13 char **strframe = NULL; 14 UINT32 i = 0, j = 0; 15 16 size = backtrace(array, 10); 17 strframe = (char **)backtrace_symbols(array, size); 18 19 printf("print call frame now: 0x%x\n", fun3); 20 for(i = 0; i < size; i++) 21 { 22 printf("frame %d -- %s\n", i, strframe[i]); 23 } 24 25 if(strframe) 26 { 27 free(strframe); 28 strframe = NULL; 29 } 30 } 31 32 void fun2(void) 33 { 34 printf("fun2 0x%x\n", fun2); 35 fun3(); 36 } 37 38 void fun1(void) 39 { 40 printf("fun1 0x%x\n", fun1); 41 fun2(); 42 } 43 44 int main(void) 45 { 46 printf("main 0x%x\n", main); 47 fun1(); 48 return 0; 49 }
[xxxzte.intra@桌面]$ gcc -g -rdynamic backTrace.c
[xxx@zte.intra@桌面]$ ./a.out
main 0x4009b8
fun1 0x400998
fun2 0x400978
print call frame now: 0x4008a6
frame 0 -- ./a.out(fun3+0x4a) [0x4008f0]
frame 1 -- ./a.out(fun2+0x1d) [0x400995]
frame 2 -- ./a.out(fun1+0x1d) [0x4009b5]
frame 3 -- ./a.out(main+0x1d) [0x4009d5]
frame 4 -- /usr/lib64/libc.so.6(__libc_start_main+0xf1) [0x7f2381398401]
frame 5 -- ./a.out(_start+0x2a) [0x4007da]
[xxx@zte.intra@桌面]$ addr2line 0x4009d5 -e ./a.out -f
main
/home/xxx@zte.intra/桌面/backTrace.c:48