1

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)

stardust
  • 5,918
  • 1
  • 18
  • 20

1 Answers1

2

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.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362
  • I absolutely agree it is an unusual requirement. I was just not 100% not sure that it was not possible. It can definitely help when you are consuming other providers libraries on different platforms (e.g. they provide .so and .a but only .a and no .dll on Windows ) – stardust Feb 13 '22 at 13:19