gpt4 book ai didi

C++ 从 std::exception 获取调用堆栈

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:37:00 27 4
gpt4 key购买 nike

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

最佳答案

如果您使用的是 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);
}

我自己没试过,不知道行不行。

关于C++ 从 std::exception 获取调用堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3378401/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com