Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I build a shared library by linking static libraries?

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++?

like image 495
flyingbin Avatar asked Jan 10 '12 18:01

flyingbin


People also ask

Can you statically link a shared library?

You can't statically link a shared library (or dynamically link a static one). The flag -static will force the linker to use static libraries (. a) instead of shared (. so) ones.

What happens when you link a static library?

Static linking increases the file size of your program, and it may increase the code size in memory if other applications, or other copies of your application, are running on the system. This option forces the linker to place the library procedures your program references into the program's object file.

Can you link a static library to a dynamic library?

When you want to “link a static library with dynamic library”, you really want to include the symbols defined in the static library as a part of the dynamic library, so that the run-time linker gets the symbols when it is loading the dynamic library.

How are shared libraries created?

To create a shared library in C++ using G++, compile the C++ library code using GCC/ G++ to object file and convert the object file to shared (. SO) file using gcc/ g++. The code can be used during the compilation of code and running executable by linking the . SO file using G++.

What is the difference between shared and static library?

Static libraries, while reusable in multiple programs, are locked into a program at compile time. Dynamic, or shared libraries, on the other hand, exist as separate files outside of the executable file.

Which of the following options is necessary to create a shared library?

The -shared or -dynamiclib option is required to create a shared library.


2 Answers

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.

like image 159
R.. GitHub STOP HELPING ICE Avatar answered Sep 30 '22 01:09

R.. GitHub STOP HELPING ICE


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
like image 35
Joachim Isaksson Avatar answered Sep 30 '22 03:09

Joachim Isaksson