Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ linker order for multiple defined symbols

If I have the same symbol defined in an object file and in a library the GNU linker takes the symbol from the object file. Consider this example:

g++ -L"dir/to/lib" -o Executable Test.o foo.o -lMyLib

If I have defined a function foo with the same signature in both foo.cpp and in a source file "MyLib" was compiled from, the GNU linker always prefers the one from the former if I use this order.

Is this behaviour GNU toolchain specific? Do you know from other linkers that behave the same way? Is this anywhere documented (GNU documentation, C++ standard)? I couldn't find anything...

I would like to use this feature to replace/mock certain functions while doing unit testing (aka link seam).

like image 675
Mike Avatar asked Dec 10 '22 04:12

Mike


1 Answers

From http://gcc.gnu.org/onlinedocs/gcc/Link-Options.html:

"the linker searches and processes libraries and object files in the order they are specified"

like image 188
Ofir Avatar answered Dec 25 '22 07:12

Ofir