在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。