Reputation: 8304
As soon as I upgraded my Ubuntu distro to 11.10, I started seeing strange linker behavior with gcc. I was able to fix the problem by moving my -l
arguments to the end of the gcc command (my problem was similar to the one described in this thread, and the proposed solution worked for me...thanks!).
My question is...why did I have this problem only now? I've been developing and testing this code on OS X and Ubuntu for a while: I never knew that -l
commands are supposed to go after your .c files, but even so, this never gave me problems before. I'm guessing it has more to do with the version of GCC than the Ubuntu release version.
Is this newer version simply enforcing this requirement more strictly than earlier versions?
Upvotes: 21
Views: 12669
Reputation: 1830
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
Upvotes: 4
Reputation: 1766
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:
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...
Upvotes: 5