概述
#include <iostream>
#include <iomanip>
#include <unwind.h>
#include <dlfcn.h>
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;
}
size_t captureBacktrace(void **buffer, size_t max) {
BacktraceState state = {buffer, buffer + max};
_Unwind_Backtrace(unwindCallback, &state);
return state.current - buffer;
}
void dumpBacktrace(std::ostream &os, void **buffer, size_t count) {
for (size_t idx = 0; idx < count; ++idx) {
const void *addr = buffer[idx];
const char *symbol = "";
Dl_info info;
if (dladdr(addr, &info) && info.dli_sname) {
symbol = info.dli_sname;
}
os << " #" << std::setw(2) << idx << ": " << addr << " " << symbol << "n";
}
}
使用如下:
const size_t max = 30;
void* buffer[max];
std::ostringstream oss;
dumpBacktrace(oss, buffer, captureBacktrace(buffer, max));
printf("tracerace:%s",oss.str().c_str());
最后
以上就是矮小帅哥为你收集整理的c/c++输出调用栈信息的全部内容,希望文章能够帮你解决c/c++输出调用栈信息所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复