Convert a Static Library to a Shared Library?

CLinuxShared LibrariesStatic Libraries

C Problem Overview


I have a third-party library which consists mainly of a large number of static (.a) library files. I can compile this into a single .a library file, but I really need it to be a single .so shared library file.

Is there any way to convert a static .a file into a shared .so file? Or more generally is there a good way to combine a huge number of static .a files with a few .o object files into a single .so file?

C Solutions


Solution 1 - C

Does this (with appropriate -L's of course)

gcc -shared -o megalib.so foo.o bar.o -la_static_lib -lb_static_lib

Not do it?

Solution 2 - C

You can't do this if objects within static library was compiled without -fPIC or like.

Solution 3 - C

g++ -shared -o megalib.so foo.o bar.o -Wl,--whole-archive -la_static_lib -lb_static_lib -Wl,--no-whole-archive -lc_static_lib -lother_shared_object

I'm not sure about gcc, but for g++ I had to add the --whole-archive linker option to include the objects from the static libraries in the shared object. The --no-whole-archive option is necessary if you want to link to libc_static_lib.a and libother_shared_object.so, but not include them as a whole in megalib.so.

Solution 4 - C

ar -x can be also useful if you want to focus on specific objects from your .as and you don't want to add anything on your own.

Examples:

ar -x lib***.a
gcc -shared *.o -o lib***.so

Solution 5 - C

ar -x lib***.a
gcc -shared *.o -o lib***.so

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEli CourtwrightView Question on Stackoverflow
Solution 1 - CdicroceView Answer on Stackoverflow
Solution 2 - Cvitaly.v.chView Answer on Stackoverflow
Solution 3 - CCalmView Answer on Stackoverflow
Solution 4 - CAnastasios AndronidisView Answer on Stackoverflow
Solution 5 - CArtur ShaikhullinView Answer on Stackoverflow