Linking libraries with gcc: order of arguments

With gcc but also other compilers (e.g. clang), the order of linker command arguments does matter. As a rule of thumb, I would use the following order when composing the linker command:

  1. Object files (*.o)
  2. Static libraries (*.a)
  3. Shared libraries (*.so)

The order of shared libraries does matter as well. If libfoo.so depends on libbar.so, you should list -lfoo before -lbar.

This can get quite complex if you don't know the exact dependencies. The following command on linux could help:

ldd /path/to/libfoo.so

This lists all shared libs on which libfoo.so depends.

As to your question why this problem popped up with your particular gcc version, it's hard to tell without knowing which libs your application requires. But if you apply the order like I described above, it should work for both older and newer gcc versions.

Hint: CMake, if used correctly, can handle all that dependency stuff for you...


I suspect your problem was because Ubuntu v11.10's GCC v4.6 enabled -Wl,--as-needed by default, and that made the linker sensitive to the ordering of libraries on the command line.

  • Ubuntu v11.10 included GCC v4.6 as the default compiler [1].

  • Ubuntu v11.10's GCC enabled -Wl,--as-needed by default [2].

  • "The --as-needed option also makes the linker sensitive to the ordering of libraries on the command-line. You may need to move some libraries later in the command-line, so they come after other libraries or files that require symbols from them." [3]

[1] https://wiki.ubuntu.com/OneiricOcelot/ReleaseNotes#GCC_4.6_Toolchain

[2] https://wiki.ubuntu.com/ToolChain/CompilerFlags#A-Wl.2C--as-needed

[3] https://wiki.ubuntu.com/NattyNarwhal/ToolchainTransition