Search code examples
gcclinkerstatic-linking

Using -Lpath -lname options vs. providing the library file directly


Recently, I got into a problem with linking and VPATH with the side effect of this question.

Assume you are implementing a library and you want to link your tests with it. You have two options (that I know of):

  • Using -L and -l options:

    gcc main.o -Lpath/to/lib -lname
    
  • Giving the library file directly:

    gcc main.o path/to/lib/libname.a
    

My question is, given the fact that I am linking to my own library under implementation (and not one that is installed, and therefore placed in /usr/lib for example), is there any advantage in choosing either method?

Currently I use the first method, but the second method allows me to solve the problem I had with VPATH. I am particularly interested in knowing whether there are certain caveats with the second method, before making the switch.


Solution

  • The only difference I can think of is that the first method allows the linker to choose a shared library if it exists. The second doesn't, because you explicitly name a .a static archive.

    If you were using a shared library there is a difference: if the second form names a shared library without a soname the application would have a DT_NEEDED tag of path/to/lib/libname.so, but for the first form would have the tag with the value libname.so. (If the shared library has a soname that would be used for the DT_NEEDED tag however the path was specified.)