- 在程序运行时打印相关调用栈信息(函数名,文件行号等),便于梳理调用逻辑等
#include <stdio.h>
#include <execinfo.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define MAX_FRAMES 128
#define BUFFER_SIZE 512
void PrintStackTrace()
{
void *callstack[MAX_FRAMES];
int frames = backtrace(callstack, MAX_FRAMES);
if (frames <= 0)
{
fprintf(stderr, "Failed to retrieve backtrace\n");
return;
}
char **strs = backtrace_symbols(callstack, frames);
if (strs == NULL)
{
fprintf(stderr, "Failed to retrieve backtrace symbols\n");
return;
}
printf("Stack trace:\n");
for (int i = 0; i < frames; ++i)
{
char *address = strchr(strs[i], '[');
if (address != NULL)
{
*address = '\0';
++address;
char command[BUFFER_SIZE];
snprintf(command, BUFFER_SIZE, "addr2line -f -e ./stack %s", address);
FILE *fp = popen(command, "r");
if (fp != NULL)
{
char buffer[BUFFER_SIZE];
while (fgets(buffer, BUFFER_SIZE, fp) != NULL)
{
printf(" %s", buffer);
}
pclose(fp);
}
else
{
fprintf(stderr, "Failed to execute addr2line command\n");
}
}
}
free(strs);
}
void Bar()
{
PrintStackTrace();
}
void Foo()
{
Bar();
}
int main()
{
Foo();
return 0;
}
gcc -g stack.c -o stack -rdynamic
./stack