如何使用boost.stacktrace打印函数名称?

时间:2018-10-13 14:21:35

标签: c++ boost

我正在使用boost.stacktrace打印异常的堆栈跟踪,这是代码:

#include <iostream>
#include <boost/stacktrace.hpp>

void bar() {
    throw std::runtime_error("A runtime error.");
}

void foo() {
    bar();
}

int main (int argc, char* argv[]) {
    try {
        foo();
    } catch (std::exception& e) {
        std::cout << e.what() << std::endl;
        std::cout << boost::stacktrace::stacktrace() << std::endl;
    }
    return 0;
}

我使用以下命令编译并执行了它:

clang++ -g hello.cpp -ldl -lboost_stacktrace_backtrace -lbacktrace
./a.out

我得到以下结果:

A runtime error.
 0# 0x000056335CB25570 in ./a.out
 1# __libc_start_main in /usr/lib/libc.so.6
 2# 0x000056335CB2534E in ./a.out

不好,函数名称被替换为地址。我想要的是这样的东西(显示在boost.stacktrace's website中):

0# bar(int) at /path/to/source/file.cpp:70
1# bar(int) at /path/to/source/file.cpp:70
2# bar(int) at /path/to/source/file.cpp:70
3# bar(int) at /path/to/source/file.cpp:70
4# main at /path/to/main.cpp:93
5# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6
6# _start

我该怎么做?

1 个答案:

答案 0 :(得分:0)

您需要在.cpp文件中定义此宏

#define BOOST_STACKTRACE_USE_ADDR2LINE

然后在编译时定义

-DBOOST_STACKTRACE_BACKTRACE_INCLUDE_FILE="</usr/lib/gcc/x86_64-linux-gnu/9/include/backtrace.h>"

您可以ls /usr/lib/gcc/x86_64-linux-gnu/查看所拥有的版本。就我而言,是9