addr2line获取行号始终返回0

时间:2018-08-17 03:13:43

标签: c++ linux debugging

我使用以下代码获取追溯

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);
    for (i = 1; i < bt_size; i++) {
        size_t len = strlen(bt_syms[i]);
        std::cout << bt_syms[i] << std::endl;
    }
    free(bt_syms);
}


int main() {
    print_backtrace();
    return 0;
}

,输出为:

/home/roroco/Dropbox/c/ro-c/cmake-build-debug/ex/test_backtrace_with_line_number
/home/roroco/Dropbox/c/ro-c/cmake-build-debug/ex/test_backtrace_with_line_number(main+0x9) [0x400d0b]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0) [0x7ff20985c830]
/home/roroco/Dropbox/c/ro-c/cmake-build-debug/ex/test_backtrace_with_line_number(_start+0x29) [0x400b29]

当我使用addr2line将addr转换为下面的行号时,总是返回“ ??:0”,如何获得真实的行号?

roroco@roroco ~/Dropbox/c/ro-c $ addr2line -e /home/roroco/Dropbox/c/ro-c/cmake-build-debug/CMakeFiles/3.12.0/CompilerIdCXX/a.out 0x400d0b
??:0
roroco@roroco ~/Dropbox/c/ro-c $ addr2line -e /home/roroco/Dropbox/c/ro-c/cmake-build-debug/CMakeFiles/3.12.0/CompilerIdCXX/a.out 0x7ff20985c830
??:0
roroco@roroco ~/Dropbox/c/ro-c $ addr2line -e /home/roroco/Dropbox/c/ro-c/cmake-build-debug/CMakeFiles/3.12.0/CompilerIdCXX/a.out 0x400b29
??:0

1 个答案:

答案 0 :(得分:1)

事实证明

/home/roroco/Dropbox/c/ro-c/cmake-build-debug/CMakeFiles/3.12.0/CompilerIdCXX/a.out

不是您构建的可执行文件(它对应于CMake进行的编译器测试)。

相反,您可以尝试以下操作:

addr2line -e /home/roroco/Dropbox/c/ro-c/cmake-build-debug/ex/test_backtrace_with_line_number

其中test_backtrace_with_line_number对应于您生成的可执行文件。它应该是与add_executable中的CMakeLists.txt命令关联的名称