Convert Shared Library to Static Library

Convert a Static Library to a Shared Library?

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?

Why shared library linked with static library behaves like it was linked with dynamic one?

Shared libraries and static libraries are very different beasts.

A static library is literally an archive file, similar to a .tar file, whose contents are object files. Typically these are augmented with an index of the external symbols defined in the object files. During static linking, the linker extracts some or all of those object files from the library and links those with any other specified objects, pretty much as if the extracted object files had been specified directly. There is no inherent distinction between external symbols based on which object provided them, or on whether that object was drawn from a (static) library.

Shared libraries are integrated objects, very much along the lines of programs. They can be executable programs. There are no individual object files within. In shared-library formats that feature position-independent code, all external symbols provided by the library must be position-independent.

When you link a static library into a shared one, you are asking the linker to include the contents of some or all of the object files from the static library in the resulting shared library. That's the only way it can work. The external symbols resolved from the static library will be external symbols in the shared one, too, so references to them need to be relative, including from other functions in the shared lib.

Convert a Static Library to a Shared Library (create libsome.so from libsome.a): where's my symbols?

Assuming you're using the GNU linker, you need to specify the --whole-archive option so that you'll get all the contents of the static archive. Since that's an linker option, you'll need -Wl to tell gcc to pass it through to the linker:

g++ -std=c++98 -fpic -g -O1 -shared -o libsome.so -Wl,--whole-archive libsome.a

If you were doing something more complicated where you want all of library some but only the part of library support needed by libsome, you would want to turn off whole archive after you've used it on libsome:

... -Wl,--whole-archive libsome.a -Wl,--no-whole-archive libsupport.a

If you're not using the GNU linker, you'll need to see if your linker supports it and what it's called. On the Sun linker, it's called -z allextract and -z defaultextract.



Related Topics



Leave a reply



Submit