在C++中,获取堆栈跟踪信息通常需要使用第三方库或操作系统特定的API
backtrace
和backtrace_symbols
函数(仅限于GNU/Linux):#include <execinfo.h>
#include<iostream>
void printStackTrace() {
const int maxFrames = 64;
void* frames[maxFrames];
int numFrames = backtrace(frames, maxFrames);
char** symbols = backtrace_symbols(frames, numFrames);
std::cout << "Stack trace:"<< std::endl;
for (int i = 0; i < numFrames; ++i) {
std::cout<< symbols[i]<< std::endl;
}
free(symbols);
}
int main() {
// ... your code ...
printStackTrace();
return 0;
}
libunwind
库(跨平台):首先,安装libunwind
库:
# Ubuntu/Debian
sudo apt-get install libunwind-dev
# Fedora/RHEL
sudo dnf install libunwind-devel
然后,编写以下代码:
#include <unwind.h>
#include <cxxabi.h>
#include<iostream>
struct BacktraceState {
void** current;
void** end;
};
static _Unwind_Reason_Code unwindCallback(struct _Unwind_Context* context, void* arg) {
BacktraceState* state = static_cast<BacktraceState*>(arg);
uintptr_t pc = _Unwind_GetIP(context);
if (pc) {
if (state->current == state->end) {
return _URC_END_OF_STACK;
} else {
*state->current++ = reinterpret_cast<void*>(pc);
}
}
return _URC_NO_REASON;
}
void printStackTrace() {
const int maxFrames = 64;
void* frames[maxFrames];
BacktraceState state = {frames, frames + maxFrames};
_Unwind_Backtrace(unwindCallback, &state);
std::cout << "Stack trace:"<< std::endl;
for (void** frame = frames; frame != state.current; ++frame) {
std::cout << *frame<< std::endl;
}
}
int main() {
// ... your code ...
printStackTrace();
return 0;
}
请注意,这些方法可能无法提供完整的堆栈跟踪信息,特别是在优化过的代码中。此外,它们可能无法处理某些类型的错误,例如堆栈溢出。在生产环境中,你可能需要使用更健壮的工具,如Valgrind或AddressSanitizer。