Prefer static libraries but fallback to shared if not found

Viewed 184

GCC (or the linker) prefers dynamic libraries over static ones by default. That means if I have

libfoo.so
libfoo.a
libbar.a

and if I am building another library libmylib.so as follows:

gcc -shared -o mylib.so ... -lfoo -lbar

the linker will link to libfoo.so (by preference) and libbar.a since that is the only one available.


One can force linking of static libraries by specifying -static (or -Wl,-Bstatic) instead.

gcc -shared -o mylib.so ... -static -lfoo -lbar

This all works fine and will link to static versions of both libs.

However if I do not have the static libs it will not fallback to the shared libs. That is if I only have

libfoo.so
libbar.a

the linking will fail because of missing libfoo.a instead of falling back to libfoo.so since it is the only one available.


Is there anyway to force this behavior where static libs are preferred but shared libs are picked if there is no static one that matches? (without having to explicitly specify -Wl,-Bdynamic manually for every such case)

1 Answers

Is there anyway to force this behavior where static libs are preferred but shared libs are picked if there is no static one that matches?

Not that I know of.

This is quite an unusual requirement. Usually you want to link everything dynamically, except a few libraries (which you know in advance) which you want to link in statically.

For a solution to that problem, see this answer.

Related