c++ - 如何从链接器错误转到源代码中的代码行?

标签 c++ linux gcc linker g++

链接器产生这种输出

/var/tmp/ccITB4j2.o: In function `main':
/var/tmp/ccITB4j2.o(.text+0x4): undefined reference to `myFunction(void)'

如何找到.text+0x4处的指令对应的源代码行,真正调用该函数的地方?

最佳答案

首先,您问题的另一个答案是错误的:在 Linux 上您确实从链接器获取文件和行号:

$ cat foo.cc
extern int myFunction(void);

int main()
{
  return myFunction();
}
$ g++ -g foo.cc
/tmp/cc3twlhL.o: In function `main':
/tmp/foo.cc:5: undefined reference to `myFunction()'
collect2: ld returned 1 exit status

以上输出来自 gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3 和链接器 GNU ld (GNU Binutils for Ubuntu) 2.22,但这有对于更旧版本的 GCC 和 ld 也是如此。

你没有得到文件/行的原因一定是

  • 您没有使用 -g 标志,或者
  • 你有一个真的旧的ld,或者
  • 你配置了你的 ld 不支持调试(我不确定这是否可能)。

但是,即使您的 ld 拒绝告诉您文件和行,也不会全部丢失。您可以将源代码编译成对象,然后使用 objdump -rdS foo.o 获取相同的信息:

g++ -g -c foo.cc
objdump -rdS foo.o

Disassembly of section .text:

0000000000000000 <main>:
extern int myFunction(void);

int main()
{
   0:   55                      push   %rbp
   1:   48 89 e5                mov    %rsp,%rbp
  return myFunction();
   4:   e8 00 00 00 00          callq  9 <main+0x9>
            5: R_X86_64_PC32    _Z10myFunctionv-0x4
}
   9:   5d                      pop    %rbp
   a:   c3                      retq

在上面的输出中,您可以清楚地看到哪一行源代码引起了对 _Z10myFunctionv 的引用(这是 myFunction(void)C++ 错位名称>) 在目标文件中发出。

关于c++ - 如何从链接器错误转到源代码中的代码行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15889650/

相关文章:

linux - linux find中排除隐藏文件和文件夹

c++ - cin 在 Windows 上不能使用空字符串 when_GLIBCXX_DEBUG?

我们可以写多行宏而末尾没有反斜杠吗?

c++ - Qtableview搜索栏

c++ - C++计算标准输入中的单词数

c++ - 读取和写入缓冲区

c++ - 如何设置和清除串口的RTS线。 C++ POSIX

linux - 与排序命令不一致的答案

linux - 定位 typesizes.h

c++ - 为什么 GCC 似乎没有文件系统标准库?