Search code examples
gccstatic-librariesldstatic-linkingunix-ar

Two ways of linking to static libraries


Here are a couple of ways to use functions from a static library, built with ar (i.e. libSOMTEHING.a):

ld -o result myapp.o  -Lpath/to/library -lname 
ld -o result myapp.o  path/to/library/libname.a 

Since we omit any dynamic libraries from the command line, this should build a static executable.

What are the differences? For example, are the whole libraries linked in the executable, or just the needed functions? In the second example, does switching the places of the lib and the object file matter?

(PS: some non-GNU ld linkers require all options like -o to be before the first non-option filename, in which case they'd only accept -L... -lname before myapp.o)


Solution

  • In the first line, a search for a dynamic library (libname.so) occurs before the static library (libname.a) within a directory. Also, the standard lib path is also searched for libname.*, not just /path/to/library.

    From "man ld"

    On systems which support shared libraries, ld may also search for files other than libnamespec.a. Specifically, on ELF and SunOS systems, ld will search a directory for a library called libnamespec.so before searching for one called libnamespec.a. (By convention, a ".so" extension indicates a shared library.)

    The second line forces the linker to use the static library at path/to/lib.

    If there is no dynamic library built (libname.so), and the only library available is path/to/library/libname.a, then the two lines will produce the same "result" binary.