Proper way to link a static library using GCC

Nairou picture Nairou · Mar 31, 2012 · Viewed 32k times · Source

Why is it that some static libraries (lib*.a) can be linked in the same way that shared libraries (lib*.so) are linked (ld -l switch), but some can not?

I had always been taught that all libraries, static or not, can be linked with -l..., however I've run into one library so far (GLFW), which does nothing but spew "undefined reference" link errors if I attempt to link it this way.

According to the response on this question, the "proper" way to link static libraries is to include them directly, along with my own object files, rather than using -l. And, in the case of the GLFW library, this certainly solves the issue. But every other static library I'm using works just fine when linked with -l.

So:

  • What could cause this one library to not work when linked rather than included directly? If I knew the cause, maybe I could edit and recompile the library to fix the issue.
  • Is it true that you're not supposed to link static libraries the same way you link shared libraries? (And if not, why not?)
  • Is the linker still able to eliminate unused library functions from the output executable when the library is directly included in this way?

Answer

Nairou picture Nairou · Apr 1, 2012

Thanks for the replies! Turns out the problem was due to link order. Apparently, if you use a library which in turn has other library dependencies, those other dependencies must be listed after the library, not before as I had been doing. Learned something new!