见backtrace()。
例如
#include <execinfo.h>
#include <stdio.h>
void bar() {
void* callstack[128];
int i, frames = backtrace(callstack, 128);
char** strs = backtrace_symbols(callstack, frames);
for (i = 0; i < frames; ++i) {
printf("%s\n", strs[i]);
}
free(strs);
}
int foo() {
bar();
return 0;
}
int main() {
foo();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
0 a.out 0x0000000100000e24 bar + 28
1 a.out 0x0000000100000e81 foo + 14
2 a.out 0x0000000100000e96 main + 14
3 a.out 0x0000000100000e00 start + 52
4 ??? 0x0000000000000001 0x0 + 1
Run Code Online (Sandbox Code Playgroud)
看:
你在glibc中有回溯函数.它可以让您使用调用函数或方法进行完整跟踪.
如果你只是想调用者,这里还有特定的功能在GCC只是这样的:
__builtin_frame_address(int level);
Run Code Online (Sandbox Code Playgroud)
有了level == 1你的来电功能.有关如何使用它的更多详细信息,请参阅此文章.
以下是文档中的示例程序:
#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>
/* Obtain a backtrace and print it to stdout. */
void
print_trace (void)
{
void *array[10];
size_t size;
char **strings;
size_t i;
size = backtrace (array, 10);
strings = backtrace_symbols (array, size);
printf ("Obtained %zd stack frames.\n", size);
for (i = 0; i < size; i++)
printf ("%s\n", strings[i]);
free (strings);
}
/* A dummy function to make the backtrace more interesting. */
void
dummy_function (void)
{
print_trace ();
}
int
main (void)
{
dummy_function ();
return 0;
}
Run Code Online (Sandbox Code Playgroud)