简单的应用
一个简单的示例程序,实现一个异常类,这个异常类被抛出时记录了当时的调用栈信息。
/* show_bt.cpp */
#include <execinfo.h>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class MyException {
public:
MyException();
virtual ~MyException();
virtual string show_backtrace() const;
protected:
static const int BT_SIZE=64;
void * bt_info[BT_SIZE];
int bt_size;
};
MyException::MyException():bt_size(0) {
bt_size = backtrace(bt_info, BT_SIZE);
}
MyException::~MyException() {}
string MyException::show_backtrace() const {
string bt_string;
ostringstream oss;
for (int i = 0; i < bt_size; ++i) {
oss << bt_info[i] <<" ";
}
bt_string = oss.str();
return bt_string;
}
void f1();
void f2();
void f3();
void f1() { f2();}
void f2() { f3();}
void f3() { throw MyException(); }
int main(int argc, char * argv[])
{
try {
f1();
}
catch (const MyException &e) {
cout << e.show_backtrace() <<endl;
}
return 0;
}
编译时打开调试选项(-g),addr2line程序需要可执行文件中的调试信息才能进行“翻译”。
g++ -g -rdynamic -o show_bt show_bt.cpp
$ g++ -g -o show_bt show_bt.cpp 运行程序输出如下,
$ ./show_bt
0x40109a 0x4010c8 0x401103 0x40110f 0x401127 0x2b196ec06994 0x400d89 将输出的调用栈地址信息传给addr2line程序,
$ addr2line -f -C -e show_bt -a 0x40109a 0x4010c8 0x401103 0x40110f 0x401127 0x2b196ec06994 0x400d89
MyException
/x/home/hohua/playground/backtrace/show_bt.cpp:20
f3()
/x/home/hohua/playground/backtrace/show_bt.cpp:43
f2()
/x/home/hohua/playground/backtrace/show_bt.cpp:41
f1()
/x/home/hohua/playground/backtrace/show_bt.cpp:39
main
/x/home/hohua/playground/backtrace/show_bt.cpp:48
??
??:0
_start
??:0
有时候,程序需要拷贝到远程主机运行。含有调试信息的程序体积太大,可以通过下面的命令“剥离”调试信息,
objcopy --strip-all exe-debug exe-striped 得到调用栈的地址信息后,再在本地对含有调试信息的