Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to link a static library using GCC

Tags:

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?
like image 826
Nairou Avatar asked Mar 31 '12 01:03

Nairou


People also ask

Which gcc option is used to link the library?

The -l option tells gcc to link in the specified library.


2 Answers

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!

like image 55
Nairou Avatar answered Oct 11 '22 10:10

Nairou


Have you cared to indicate to GCC the path of your library (using -L) ? By using -l solely, GCC will only be able to link libraries available in standard directories.

-L[path] -l[lib] 
like image 32
Vincent L. Avatar answered Oct 11 '22 12:10

Vincent L.