特定於Linux的backtrace()
和backtrace_symbols()
允許您生成程序的調用跟蹤。但是,它只打印功能地址,而不是我的程序的名稱。我怎樣才能讓他們打印函數名稱呢?我試着用-g
以及-ggdb
來編譯程序。測試用例下面只是打印此:如何使backtrace()/ backtrace_symbols()打印函數名?
BACKTRACE ------------ ./a.out() [0x8048616] ./a.out() [0x8048623] /lib/libc.so.6(__libc_start_main+0xf3) [0x4a937413] ./a.out() [0x8048421] ----------------------
我願意第一個2項也顯示函數名,foo
和main
代碼:
#include <execinfo.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
static void full_write(int fd, const char *buf, size_t len)
{
while (len > 0) {
ssize_t ret = write(fd, buf, len);
if ((ret == -1) && (errno != EINTR))
break;
buf += (size_t) ret;
len -= (size_t) ret;
}
}
void print_backtrace(void)
{
static const char start[] = "BACKTRACE ------------\n";
static const char end[] = "----------------------\n";
void *bt[1024];
int bt_size;
char **bt_syms;
int i;
bt_size = backtrace(bt, 1024);
bt_syms = backtrace_symbols(bt, bt_size);
full_write(STDERR_FILENO, start, strlen(start));
for (i = 1; i < bt_size; i++) {
size_t len = strlen(bt_syms[i]);
full_write(STDERR_FILENO, bt_syms[i], len);
full_write(STDERR_FILENO, "\n", 1);
}
full_write(STDERR_FILENO, end, strlen(end));
free(bt_syms);
}
void foo()
{
print_backtrace();
}
int main()
{
foo();
return 0;
}
的可能重複[如何獲得更詳細的回溯(http://stackoverflow.com/questions/5945775/how-to-get-more-detailed-backtrace) – Nemo
http://stackoverflow.com/questions/105659/how-can-one-grab-a-stack-trace-in-c –