我可以通过链接静态库来构建共享库吗?

时间:2022-12-14 18:54:18

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

我有一堆静态库(* .a),我想构建一个共享库(* .so)来链接这些静态库(* .a)。我怎么能用gcc / g ++这样做?

2 个解决方案

#1


14  

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.

您可以(只提取所有.o文件并使用-shared链接它们以生成.so),但它是否有效以及它的工作原理取决于平台以及静态库是否编译为与位置无关的代码(PIC)。在某些平台(例如x86_64)上,非PIC代码在共享库中无效且不起作用(实际上我认为链接器将拒绝生成.so)。在其他平台上,非PIC代码将在共享库中工作,但是库的内存中副本在使用它的不同程序之间不可共享,甚至不能在同一程序的不同实例之间共享,因此会导致巨大的内存膨胀。

#2


6  

I can't see why you couldn't just build the files of your dynamic library to .o files and link with;

我不明白为什么你不能只将动态库的文件构建到.o文件并链接;

gcc -shared *.o -lstaticlib1 -lstaticlib2 -o mylib.so

#1


14  

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.

您可以(只提取所有.o文件并使用-shared链接它们以生成.so),但它是否有效以及它的工作原理取决于平台以及静态库是否编译为与位置无关的代码(PIC)。在某些平台(例如x86_64)上,非PIC代码在共享库中无效且不起作用(实际上我认为链接器将拒绝生成.so)。在其他平台上,非PIC代码将在共享库中工作,但是库的内存中副本在使用它的不同程序之间不可共享,甚至不能在同一程序的不同实例之间共享,因此会导致巨大的内存膨胀。

#2


6  

I can't see why you couldn't just build the files of your dynamic library to .o files and link with;

我不明白为什么你不能只将动态库的文件构建到.o文件并链接;

gcc -shared *.o -lstaticlib1 -lstaticlib2 -o mylib.so