gpt4 book ai didi

c - 如何让 backtrace()/backtrace_symbols() 打印函数名?

转载 作者:IT老高 更新时间:2023-10-28 12:25:13 25 4
gpt4 key购买 nike

Linux 特定的 backtrace()backtrace_symbols() 允许您生成程序的调用跟踪。但是,它只打印函数地址,而不是我的程序的名称。我怎样才能让他们也打印函数名称?我试过用 -g-ggdb 编译程序。下面的测试用例只是打印这个:

    BACKTRACE ------------    ./a.out() [0x8048616]    ./a.out() [0x8048623]    /lib/libc.so.6(__libc_start_main+0xf3) [0x4a937413]    ./a.out() [0x8048421]    ----------------------    

I'd want the first 2 items to also show the function names, foo and main

Code:

#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;
}

最佳答案

符号取自动态符号表;您需要 gcc-rdynamic 选项,这使它向链接器传递一个标志,以确保将 所有 符号放置在表中。

(参见 Link OptionsGCC manual 页面和/或 Backtracesglibc manual 页面。)

关于c - 如何让 backtrace()/backtrace_symbols() 打印函数名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6934659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com