I use following code
#include <boost/stacktrace.hpp>
#include <iostream>
#include <stdexcept>
// Define a custom exception type
struct CustomException : std::runtime_error {
CustomException(const std::string& msg) : std::runtime_error(msg) {}
};
// Function to throw an error with message and stack trace
void throw_err(const std::string& err_msg) {
// Capture the stack trace
boost::stacktrace::stacktrace trace;
// Formulate the error message
std::string full_msg = "Error: " + err_msg + "\n";
// Append the stack trace to the error message
full_msg += "Stack Trace:\n";
for (const auto& frame : trace) {
full_msg += " " + frame.name() + " at " + frame.source_file() + ":" + std::to_string(frame.source_line()) + "\n";
}
// Throw the custom exception with the error message
throw CustomException(full_msg);
}
int main() {
try {
throw_err("An error occurred!");
} catch (const CustomException& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
it out:
/home/roroco/Dropbox/cpp/cpp_lib/cmake-build-debug/draft/draft/test_out_backtrace
Error: An error occurred!
Stack Trace:
at :0
at :0
__libc_start_main at :0
at :0
I hope it out real err source file and line num, how to do
I use g++ cli reproduce this err, no any err is raised, so how to fix it
/tmp $ g++-13 -I/home/roroco/Dropbox/cpp/cpp-global-deps/boost_1_85_0/dist/include -o test_out_backtrace /home/roroco/Dropbox/cpp/cpp_lib/draft/draft/test_out_backtrace.cpp -ldl
/tmp $ ./test_out_backtrace
Error: An error occurred!
Stack Trace:
at :0
at :0
__libc_start_main at :0
at :0
-gflag? That tells the compiler to add debug information.