我希望有一种方法在抛出异常时向用户报告堆栈跟踪。最好的方法是什么?它是否需要大量额外的代码?

回答问题:

如果可能的话,我希望它是便携的。我想让信息弹出,这样用户就可以复制堆栈跟踪,并在出现错误时通过电子邮件发送给我。


当前回答

AFAIK libunwind非常便携,到目前为止我还没有找到更容易使用的东西。

其他回答

如果你使用的是Boost 1.65或更高版本,你可以使用Boost::stacktrace:

#include <boost/stacktrace.hpp>

// ... somewhere inside the bar(int) function that is called recursively:
std::cout << boost::stacktrace::stacktrace();

Unix:回溯

麦克:回溯

Windows: CaptureBackTrace

Cpp-tool ex_diag -重量轻,多平台,最小的资源使用,简单和灵活的跟踪。

我推荐http://stacktrace.sourceforge.net/项目。它支持Windows, Mac OS和Linux

下面的代码在抛出异常后立即停止执行。您需要设置一个windows_exception_handler和一个终止处理程序。我在MinGW 32bits中进行了测试。

void beforeCrash(void);

static const bool SET_TERMINATE = std::set_terminate(beforeCrash);

void beforeCrash() {
    __asm("int3");
}

int main(int argc, char *argv[])
{
SetUnhandledExceptionFilter(windows_exception_handler);
...
}

检查下面的windows_exception_handler函数代码: http://www.codedisqus.com/0ziVPgVPUk/exception-handling-and-stacktrace-under-windows-mingwgcc.html