backtrace 정보 출력
2025. 3. 31. 12:58ㆍProgramming/JAVA, C++, Go, Rust
- 목차
반응형
exception 발생 시 혹은 오류 발생 시 call stack 정보를 출력하고자 하는 경우가 발생합니다.
이럴때 C++에서 다음과 같이 코드를 작성할 수 있습니다.
#include "back_trace.h"
#include <execinfo.h>
#include <ucontext.h>
#include <cxxabi.h>
#include <cstdlib>
#include <iostream>
#include <cxxabi.h>
#include <regex>
const uint32_t MAX_NUM_TRACE = 32;
std::string BackTrace::get_backtrace() {
void* callstack[MAX_NUM_TRACE];
int frames = backtrace(callstack, MAX_NUM_TRACE);
char** messages = backtrace_symbols(callstack, frames);
std::string output;
std::regex re(R"(\(([^+]+)\+0x[0-9a-f]+\))");
for (int i = 1; i < frames; ++i) {
std::cmatch match;
std::string message = messages[i];
std::string demangled;
if (std::regex_search(message.c_str(), match, re)) {
std::string mangled = match[1].str();
int status = 0;
char* demangled_name = abi::__cxa_demangle(mangled.c_str(), nullptr, nullptr, &status);
if (demangled_name && status == 0) {
demangled = demangled_name;
free(demangled_name);
} else {
demangled = mangled;
}
} else {
demangled = message;
}
output += demangled + "\n";
}
free(messages);
return output;
}
이를 빌드할때 반드시 symbol 정보를 넣어줘야 합니다.
cmake의 경우 CMakeLists.txt의 최상단에 다음과 같이 -g -rdynamic 정보를 CXX_FLAGS에 추가합니다.
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -rdynamic -g")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -rdynamic")
반응형
'Programming > JAVA, C++, Go, Rust' 카테고리의 다른 글
go get 오류 발생 시 대처 (0) | 2024.05.09 |
---|---|
go profiler pprof 사용법 (0) | 2024.02.06 |
Study stuff for Golang (0) | 2023.07.24 |
Go test: table driven test with Parallel() (0) | 2023.06.22 |
Go gotcha examples (0) | 2023.06.22 |