代码
c
复制代码
//main.c
extern void func_a();
int main (int argc, char *argv[])
{
func_a();
return 0;
}
c
复制代码
//a.c
#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>
void print_trace (void){
void *array[10];
size_t size;
char **strings;
size_t i;
size = backtrace(array, 10);
strings = backtrace_symbols(array, size);
if (NULL == strings){
perror("backtrace_synbols failed:");
}
else{
printf ("Obtained %zd stack frames.\n", size);
for (i = 0; i < size; i++)
printf ("%s\n", strings[i]);
free (strings);
strings = NULL;
}
}
extern void func_b();
void func_a(){
func_b();
}
c
复制代码
//b.c
extern void print_trace (void);
void func_c(){
print_trace();
}
void func_b(){
func_c();
}
编译
bash
复制代码
gcc -c a.c -fpic
gcc -c b.c -fpic
gcc -shared a.o -o liba.so
gcc -shared b.o -o libb.so
gcc main.c -L ./ -la -lb -o test
运行
bash
复制代码
export LD_LIBRARY_PATH=$(pwd):$LD_LIBRARY_PATH
./test
结果
bash
复制代码
./test
Obtained 8 stack frames.
/data1/liuxiaolian5/work/backtraceTest/liba.so(print_trace+0x19) [0x7fc23225317e]
/data1/liuxiaolian5/work/backtraceTest/libb.so(func_c+0x9) [0x7fc23224e11e]
/data1/liuxiaolian5/work/backtraceTest/libb.so(func_b+0xe) [0x7fc23224e12f]
/data1/liuxiaolian5/work/backtraceTest/liba.so(func_a+0xe) [0x7fc232253225]
./test() [0x40113b]
/usr/lib64/libc.so.6(+0x2d210) [0x7fc232069210]
/usr/lib64/libc.so.6(__libc_start_main+0x7c) [0x7fc2320692bc]
./test() [0x401065]