有时候调试bug需要知道某个函数从哪里调用导致出了问题的,就需要打印函数调用堆栈信息,在Linux可以使用backtrace函数来实现,下面是一个简单的例子:
#include <cstdio>
#include <cstdlib>
#include <execinfo.h>using namespace std;
void Test3(int i)
{
printf("Hello world!\n");int nptrs;
void *buffer[100];
char **strings;nptrs = backtrace(buffer, 10);
printf("backtrace returned %d address\n", nptrs);
strings = backtrace_symbols(buffer, nptrs);
for (int j = 0; j < nptrs; ++j)
{
printf("%s\n", strings[j]);
}free(strings);
}void Test2(int i)
{
Test3(i);
}void Test1(int i)
{
Test2(i);
}int main(int argc, char **argv)
{
Test1(1);return 0;
}编译:
g++ -rdynamic -o testDumpStack ./testDumpStack.cpp
执行结果: