Search code examples
gccmakefileglibc

How to statically link all libraries except glibc using make/gcc?


I am trying to compile a program to have all libraries statically inside the final binary, but I still want glibc to be dynamically linked. If I use "-static" it compiles ALL libraries statically, including glibc. Basically I need a -static parameter together with something like -exclude=glibc Would be awesome with both an example when using "make" as well as an example with pure "gcc". Running "ldd" on the final binary should show only glibc dynamically linked.


Solution

  • You can link a subset of libraries statically using -Bstatic and -Bdynamic. On the GCC command line, this looks like this (for linking statically against PCRE, just as an example):

    -Wl,-Bstatic -lpcre -Wl,-Bdynamic
    

    Note that -lanl, -ldl, -lm, -lmvec, -lnsl, -lpthread, -lresolv, -lrt, -lutil are all part of glibc and must therefore come after the -Wl,-Bdynamic (so that they are linked dynamically). For -lcrypt, this depends on the distribution.