简体   繁体   English

如何制作使用库的静态/动态库

[英]How to make a static/dynamic library that uses a library

I am making a C++ library. 我正在制作C ++库。 In the library, I am using some functions in another static library (eg ref.a). 在该库中,我正在另一个静态库中使用某些函数(例如ref.a)。

I want to generate one library file, either mylib.a or mylib.so, so that any program using my library does not need to link to the static library (ref.a). 我想生成一个库文件,即mylib.a或mylib.so,这样使用我的库的任何程序都无需链接到静态库(ref.a)。 I got some ideas from others how to link static lib into dynamic lib , like "--whole-archive", but not so clear how to do it. 我从其他人那里得到了一些有关如何将静态库链接到动态库的想法,例如“ --whole-archive”,但不清楚如何实现。

To get mylib.a, I just ar -rc mylib.a mylib.o ref.a (may not be a standard way). 要获取mylib.a,我只需ar -rc mylib.a mylib.o ref.a(可能不是标准方法)。 What about a shared lib, eg mylib.so? 共享库(例如mylib.so)呢?

To get mylib.a, I just ar -rc mylib.a mylib.o ref.a 要获取mylib.a,我只需ar -rc mylib.a mylib.o ref.a

No, that wouldn't work. 不,那是行不通的。 You have to "expand" ref.a before you include it into mylib.a: 在将ref.a包含到mylib.a中之前,必须对其进行“扩展”:

mkdir tmp.$$ && cd tmp.$$ && ar x ../ref.a &&
cd .. && ar rc mylib.a mylib.o tmp.$$/*.o &&
rm -rf tmp.$$

What about a shared lib 共享库呢

That's simpler: 那更简单:

gcc -shared -o mylib.so mylib.o -Wl,--whole-archive ref.a -Wl,--no-whole-archive

(It's very important to have the trailing -Wl,--no-whole-archive , or you may get nasty link errors from system libraries that the compiler driver adds to the end of the link.) (具有结尾的-Wl,--no-whole-archive非常重要的,否则您可能会从编译器驱动程序添加到链接末尾的系统库中得到讨厌的链接错误。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM