Violet Giraffe Violet Giraffe - 8 months ago 43
Linux Question

Why does order in which input libraries are specified matter?

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...


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.