ai make following code:
#include <iostream>
#include <execinfo.h>
#include <stdexcept>
// Function to generate and print backtrace
void print_backtrace() {
const int max_frames = 16;
void* trace[max_frames];
char** messages = nullptr;
int frames = backtrace(trace, max_frames);
messages = backtrace_symbols(trace, frames);
if (messages != nullptr) {
std::cerr << "Backtrace:n";
for (int i = 0; i < frames; ++i) {
// Print only the part of the message containing the file name and line number
std::cerr << "[" << i << "] " << messages[i] << "n";
}
free(messages);
}
}
// Utility function to throw an error with backtrace
void throw_err(const std::string& message) {
std::cerr << "Error occurred: " << message << std::endl;
print_backtrace();
throw std::runtime_error(message);
}
int main() {
try {
// Simulating an error
throw_err("An error occurred!");
} catch (const std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
return 0;
}
I out backtrace like
Backtrace:
[0] /home/roroco/Dropbox/cpp/cpp_lib/cmake-build-debug/draft/draft/test_out_backtrace(+0x1ac8) [0x555555555ac8]
[1] /home/roroco/Dropbox/cpp/cpp_lib/cmake-build-debug/draft/draft/test_out_backtrace(+0x1c33) [0x555555555c33]
[2] /home/roroco/Dropbox/cpp/cpp_lib/cmake-build-debug/draft/draft/test_out_backtrace(+0x1ccb) [0x555555555ccb]
I hope cpp out backtrace with err line num, how to do?