Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I mix static and shared-object libraries when linking?

Tags:

c

static

gcc

linker

I have a C project that produces ten executables, all of which I would like to be linked in statically. The problem I am facing is that one of these executables uses a 3rd-party library of which only the shared-object version is available.

If I pass the -static flag to gcc, ld will error saying it can't find the library in question (I presume it's looking for the .a version) and the executable will not be built. Ideally, I would like to be able to tell 'ld' to statically link as much as it can and fail over to the shared object library if a static library cannot be found.

In the interium I tried something like gcc -static -lib1 -lib2 -shared -lib3rdparty foo.c -o foo.exe in hopes that 'ld' would statically link in lib1 and lib2 but only have a run-time dependence on lib3rdparty. Unfortunatly, this did not work as I intended; instead the -shared flag overwrote the -static flag and everything was compiled as shared-objects.

Is statically linking an all-or-nothing deal, or is there some way I can mix and match?

like image 832
SiegeX Avatar asked Jun 02 '10 01:06

SiegeX


People also ask

Can you mix static and dynamic linking?

They don't mix Things get even worse if you try to mix static and dynamic linking: you can end up with multiple copies of a library in the same app. Say your app uses two libraries: FooKit and BarKit, and they both depend on a third, libCore.

Can shared library be statically linked?

You can't statically link a shared library (or dynamically link a static one).

Why do we need shared libraries in addition to static ones?

Shared libraries allow multiple programs to share a library on disk, rather than copying code into a binary, resulting in smaller binaries. Also shared libraries allow a binary to access all of the symbols in a shared library at runtime, even if a symbol was not needed at link time.

Can a static library use a dynamic library?

Yes for instance when you call windows functions from within your static lib they are normally from some dynamic library so there should be no difference.


1 Answers

Looking at this thread you can see that it can be done. The guys at GNU suggest

gcc foo.c -Wl,-Bstatic -lbar -lbaz -lqux -Wl,-Bdynamic -lcorge -o foo.exe 
like image 74
Anthony Avatar answered Sep 28 '22 06:09

Anthony