You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Boost Stacktrace输出空源文件与行号问题的解决咨询

问题:Boost Stacktrace无法显示真实的源文件及行号

我使用以下C++代码实现带栈追踪的异常:

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

// 自定义异常类型
struct CustomException : std::runtime_error {
    CustomException(const std::string& msg) : std::runtime_error(msg) {}
};

// 抛出带栈追踪的错误
void throw_err(const std::string& err_msg) {
    // 捕获栈追踪
    boost::stacktrace::stacktrace trace;

    // 构造错误信息
    std::string full_msg = "Error: " + err_msg + "\n";

    // 追加栈追踪
    full_msg += "Stack Trace:\n";
    for (const auto& frame : trace) {
        full_msg += "  " + frame.name() + " at " + frame.source_file() + ":" + std::to_string(frame.source_line()) + "\n";
    }

    // 抛出异常
    throw CustomException(full_msg);
}

int main() {
    try {
        throw_err("An error occurred!");
    } catch (const CustomException& e) {
        std::cerr << e.what() << std::endl;
    }

    return 0;
}

使用g++-13编译:

g++-13 -I/home/roroco/Dropbox/cpp/cpp-global-deps/boost_1_85_0/dist/include -o test_out_backtrace /home/roroco/Dropbox/cpp/cpp_lib/draft/draft/test_out_backtrace.cpp -ldl

运行后输出:

Error: An error occurred!
Stack Trace:
   at :0
   at :0
  __libc_start_main at :0
   at :0

栈追踪无法显示真实的源文件和行号,请问该如何修复?


解决方案

要让Boost Stacktrace显示正确的源文件和行号,需在编译时添加调试信息生成和符号保留相关选项,具体操作如下:

  • 添加-g选项:生成调试信息,这是获取源文件路径和行号的基础。
  • 添加-rdynamic选项:将所有符号(包括非导出的函数)加入动态符号表,确保栈追踪能解析到函数对应的源码位置。
  • 显式链接Boost Stacktrace后端库:根据Boost编译配置,添加-lboost_stacktrace_backtrace或-lboost_stacktrace_addr2line,保证栈追踪功能正常工作。

修改后的编译命令示例:

g++-13 -g -rdynamic -I/home/roroco/Dropbox/cpp/cpp-global-deps/boost_1_85_0/dist/include -o test_out_backtrace /home/roroco/Dropbox/cpp/cpp_lib/draft/draft/test_out_backtrace.cpp -ldl -lboost_stacktrace_backtrace

额外注意事项

  • 若使用addr2line后端,需确保系统已安装addr2line工具(通常包含在binutils软件包中)。
  • 避免使用-O2及以上等级的编译优化,这类优化可能合并或消除栈帧,导致栈追踪信息失真。若需优化,可使用-O1并配合-fno-omit-frame-pointer选项保留栈帧信息。

内容的提问来源于stack exchange,提问作者chikadance

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 20:50:09