Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to go from linker error to line of code in the sources?

The linker produces this kind of output

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

How can I find out the line of source code corresponding to the instruction at .text+0x4 where the function is actually invoked?

like image 331
Stefano Borini Avatar asked Jan 01 '26 08:01

Stefano Borini


1 Answers

First, the other answer to your question is wrong: on Linux you do get file and line number from the linker:

$ 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

Above output is from gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3 and linker GNU ld (GNU Binutils for Ubuntu) 2.22, but this has been true for much older versions of GCC and ld as well.

The reason you are not getting the file/line must be that

  • you didn't use -g flag, or
  • you have a really old ld, or
  • you have configured your ld without support for debugging (I am not sure this is even possible).

However, even if your ld is refusing to tell you the file and line, not all is lost. You can compile your source into object, then use objdump -rdS foo.o to obtain the same info:

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

In above output, you can clearly see which source line caused reference to _Z10myFunctionv (which is the C++ mangled name for myFunction(void)) to be emitted in the object file.

like image 192
Employed Russian Avatar answered Jan 03 '26 21:01

Employed Russian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!