Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
947 views
in Technique[技术] by (71.8m points)

ubuntu - Linking libraries with gcc: order of arguments

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...