查看this question和 this question我可以看到要使 backtrace_symbols()
正常工作,必须使用 -rdynamic
标志进行编译。
我已经在测试程序中尝试过它并且它可以工作,但我正在编写一个程序,该程序也是使用 -static
和 this page 编译的表示当 -static
传递给编译器/链接器时 backtrace_symbols()
不起作用。
是否有任何快速解决方法,或者我的静态链接程序中永远不会有人类可读的回溯函数?
最佳答案
答案已经在手边:在 the same page I linked in the question 中.最后,我成功使用了libunwind
。
#include <libunwind.h>
#include <stdio.h>
void do_backtrace()
{
unw_cursor_t cursor;
unw_context_t context;
unw_getcontext(&context);
unw_init_local(&cursor, &context);
while (unw_step(&cursor) > 0)
{
unw_word_t offset, pc;
char fname[64];
unw_get_reg(&cursor, UNW_REG_IP, &pc);
fname[0] = '\0';
(void) unw_get_proc_name(&cursor, fname, sizeof(fname), &offset);
printf ("%p : (%s+0x%x) [%p]\n", pc, fname, offset, pc);
}
}
int main()
{
do_backtrace();
return 0;
}
我遇到了链接错误,因为我(再次)忘记将链接器选项放在命令行的末尾。我真的不明白为什么 g++
/gcc
在忽略命令行选项时至少不发出警告。正确的编译命令行是(不需要-g
):
g++ -static unwind.cpp -o unwind -lunwind -lunwind-x86
关于c++ - 具有-static 和-rdynamic 的backtrace_symbols(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13307820/