【问题标题】:C++ get call stack from std::exceptionC++ 从 std::exception 获取调用堆栈
【发布时间】:2011-03-23 15:30:53
【问题描述】:

当 std::exception 引发时如何打印完整的调用堆栈?

【问题讨论】:

标签: c++ exception callstack


【解决方案1】:

如果您使用 g++ (gcc) 并且不介意代码不可移植,您可以尝试遵循 "tombarta" 的明智之言:

(来自 tombarta 的无耻复制):

#include <execinfo.h>
void print_trace(FILE *out, const char *file, int line)
{
    const size_t max_depth = 100;
    size_t stack_depth;
    void *stack_addrs[max_depth];
    char **stack_strings;

    stack_depth = backtrace(stack_addrs, max_depth);
    stack_strings = backtrace_symbols(stack_addrs, stack_depth);

    fprintf(out, "Call stack from %s:%d:\n", file, line);

    for (size_t i = 1; i < stack_depth; i++) {
        fprintf(out, "    %s\n", stack_strings[i]);
    }
    free(stack_strings); // malloc()ed by backtrace_symbols
    fflush(out);
}

这个我自己没试过,不知道好不好用。

【讨论】:

    猜你喜欢
    • 2012-11-26
    • 2013-04-01
    • 2010-11-21
    • 1970-01-01
    • 2021-05-26
    • 2011-01-19
    • 2014-04-26
    • 2017-03-11
    • 1970-01-01
    相关资源
    最近更新 更多