#include <stdio.h>
// We only need local unwinder.
#define UNW_LOCAL_ONLY
#include <libunwind.h>
void print_stack_trace()
{
unw_cursor_t cursor;
unw_context_t context;
// 获取当前线程的上下文
unw_getcontext(&context);
// 初始化游标
unw_init_local(&cursor, &context);
// 遍历函数调用堆栈
while (unw_step(&cursor) > 0) {
unw_word_t ip;
unw_get_reg(&cursor, UNW_REG_IP, &ip);
// 获取函数名(如果可用)
char func_name[256];
if (unw_get_proc_name(&cursor, func_name, sizeof(func_name), NULL) == 0) {
printf("Function: %s\n", func_name);
} else {
printf("Function: <unknown>\n");
}
// 打印指令指针
printf("IP: %#lx\n", (unsigned long)ip);
}
}
int main()
{
print_stack_trace();
return 0;
}
Ubuntu安装libunwind
apt-get install libunwind8-dev
编译命令:
gcc unwind.c -lunwind