I have a bunch of static libraries (*.a), and I want to build a shared library (*.so) to link against those static libraries (*.a). How can I do so in gcc/g++?
Asked
Active
Viewed 1.6k times
17
-
3.a is not a shared library. Can you give an example of what you're trying to do? – bdonlan Jan 10 '12 at 18:49
2 Answers
24
You can (just extract all the .o
files and link them with -shared
to make a .so
), but whether it works, and how well it works, depends on the platform and whether the static library was compiled as position-independent code (PIC). On some platforms (e.g. x86_64), non-PIC code is not valid in shared libraries and will not work (actually I think the linker will refuse to make the .so
). On other platforms, non-PIC code will work in shared libraries, but the in-memory copy of the library is not sharable between different programs using it or even different instances of the same program, so it will result in HUGE memory bloat.

R.. GitHub STOP HELPING ICE
- 208,859
- 35
- 376
- 711
-
3Thanks for this very useful answer! I guess this is the best explanation for this error when doing this on x86_64: 'relocation R_X86_64_32S against `g_gGlobalVariable' can not be used when making a shared object; recompile with -fPIC' – dashesy Feb 27 '13 at 16:46
-
I have to second the comment that this doesn't work on x86_64 code on Linux. On macOS, however, you can simply include the static libraries when building the dynamic one. But I have not yet managed to accomplish it on Linux. – Steven W. Klassen Dec 27 '18 at 23:36
-
I've done this in the distant past on Win32, as well. Iirr, you had to override a lot of the defaults in the IDE, but it was doable and it did work. The question comes up when building plugins. Sometimes you want to avoid collisions in shared libraries and don't have much control over the runtime deployment. – Charlie Reitzel Oct 04 '21 at 18:36
7
I can't see why you couldn't just build the files of your dynamic library to .o files and link with;
gcc -shared *.o -lstaticlib1 -lstaticlib2 -o mylib.so

Joachim Isaksson
- 176,943
- 25
- 281
- 294
-
-
1Static libraries will only pull in their code if it's actually referenced, however, so you can't just omit all `.o` – bdonlan Jan 10 '12 at 18:51
-
2Also note that if multiple instances of the same static library are present in the same executable (loaded indirectly via shared libs containing the static libs), strange things can happen – bdonlan Jan 10 '12 at 18:59
-
3@nos, PIC isn't the same as relocatable. All static libs are relocatable, but may or may not be PIC. Note that on x86 Linux (but not x86-64) non-PIC shared libs _do_ work, they just require relocations to be done at library load time, which is slow, increases memory usage, and has certain security concerns (as it requires that code pages be marked r/w while the relocation is in progress) – bdonlan Jan 10 '12 at 22:51