Why does order in which input libraries are specif

2019-01-29 03:10发布

问题:

I'm quite new to programming for Linux. You could say I'm a Windows guy. So, I was porting my project to Linux, and it almost made me insane: I'm sure I have specified all the dependencies with -l flag, and yet I'm getting "unresolved symbol" errors. Then I've found this topic, and it solved my problem: Boost linking on Linux with GCC

Could someone please explain me why does the order matter, and how exactly it matters? I'm pretty sure it is not the case with MSVC linker...

回答1:

A simple example will let you see why one-pass Unix linkers care about order.

Suppose you have main.o (generated by main.cpp) and libraries libx.a (no dependencies) and liby.a ( depends on libx called newRefX).

If the linker goes in this order, you are fine as the linker goes from 1 to 3:

  1. main.o refX=undef, refY=undef
  2. liby.a refX=undef, refY=def, newRefX=undef
  3. libx.a refX=def, refY=def, newRefX=def

But if the linker goes in this order, you run into problems with newRefX:

  1. main.o refX=undef, refY=undef
  2. libx.a refX=def, refY=undef,
  3. liby.a refX=def, refY=def, newRefX=undef

So, you can see that you want the lowest level library (the one that depends on no others) last.



回答2:

From "An Introduction to GCC - for the GNU compilers gcc and g++"

The traditional behavior of linkers is to search for external functions from left to right in the libraries specified on the command line. This means that a library containing the definition of a function should appear after any source files or object files which use it.

I believe that msvc linkers do 2 passes over the code so they might be able to resolve the symbols even when the libraries are specified in different order (reference missing ...)



回答3:

It is the way the Unix linkers work, since long time ago... See Levine's book



标签: linux linker ld