static-linkingpkg-config

How to use pkg-config to link a library statically


I'd like to link libpng found by pkg-config statically.

pkg-config --libs --static libpng

outputs

-L/usr/local/Cellar/libpng/1.6.15/lib -lpng16 -lz

I have both libpng16.a libpng16.dylib in that directory, and if I use these flags the library gets linked dynamically.

How can I tell either pkg-config or the linker (preferably in some portable-ish way) that I really want it linked statically?

I've tried adding -static before pkg-config's flags, but that makes clang's ld try and fail to link "crt0.o".


Solution

  • The pkg-config --static option relies on proper tagging in the .pc files. If providing the --static option does not return correct information necessary to link against the libpng archive, then you cannot use pkg-config for that purpose.

    I suspect libpng (along with a majority of other packages) dropped support for static linking some time after libpng 1.2. They may still provide a library archive, but the libpng pkg-config file is no longer properly tagged to support a static link. You will have to manually tell ld to use the static lib.