[英]Running function on C++ throw in gcc/linux?
Is there any way in gcc/linux to have a user-defined function called immediately after any C++ throw statement executes, but before the stack is unwound to the catch?在 gcc/linux 中是否有任何方法可以在任何 C++ throw 语句执行后立即调用用户定义的 function,但在堆栈未展开到捕获之前? (I want to capture a stacktrace.)
(我想捕获一个堆栈跟踪。)
(In gdb I can write catch throw
. Anyway to do that programmatically short of a compiler extension?) (在 gdb 中,我可以写
catch throw
。无论如何,要以编程方式完成编译器扩展吗?)
If you are using libstdc++
, you could override __cxa_throw()
.如果您使用的是
libstdc++
,则可以覆盖__cxa_throw()
。
For instance:例如:
#include <cstring>
void __cxa_throw(void *, void *, void (*)(void *)) {
std::puts("bad luck");
}
int main() {
throw 13;
}
at your throwing site you can do this:在您的投掷地点,您可以这样做:
try { throw 13; }
catch (...) { print_stack_trace(); rethrow;}
Of course, if you want this everywhere , then you'll need some automated editing to put it there (or a macro like this): untested code当然,如果你想要这个到处都是,那么你需要一些自动编辑来把它放在那里(或者像这样的宏):未经测试的代码
#define THROW(x) do { \
try {throw(x);} \
catch(...) { print_stack_trace(); rethrow;} \
} while(false)
or even simpler:甚至更简单:
#define THROW(x) do { \
print_stack_trace(); \
throw(x); \
} while(false)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.