std::stacktrace
Use case
Capture callstack for debugging/logging.
Explanation
std::stacktrace::current() captures the call stack.
Code
// std::stacktrace is not fully implemented everywhere yet.
// https://en.cppreference.com/w/cpp/compiler_support/23.html
#if defined(__linux__)
#include <print>
#include <stacktrace>
#include <string_view>
void analyzeFunction(uint64_t addr) {
std::println("Analyzing {:#x}", addr);
std::println("Callstack:\n{}", std::stacktrace::current());
}
void processSection([[maybe_unused]] std::string_view name) {
analyzeFunction(0x10001000);
}
int main() {
processSection("__TEXT");
return 0;
}
#else
int main() { return 0; }
#endif
Output
$ ./src/c++23/build/std-stacktrace
Analyzing 0x10001000
Callstack:
0# analyzeFunction(unsigned long) at :0
1# processSection(std::basic_string_view<char, std::char_traits<char> >) at :0
2# main at :0
3# __libc_start_call_main at ../sysdeps/nptl/libc_start_call_main.h:58
4# __libc_start_main_impl at ../csu/libc-start.c:360
5# _start at :0
6#