C语言 链接时可以混合静态库和共享对象库吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2954387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:33:28  来源:igfitidea点击:

Can I mix static and shared-object libraries when linking?

cgccstaticlinker

提问by SiegeX

I have a C project that produces ten executables, all of which I would like to be linked in statically. The problem I am facing is that one of these executables uses a 3rd-party library of which only the shared-object version is available.

我有一个 C 项目,它生成十个可执行文件,我想静态链接所有这些文件。我面临的问题是这些可执行文件之一使用了只有共享对象版本可用的第 3 方库。

If I pass the -staticflag to gcc, ld will error saying it can't find the library in question (I presume it's looking for the .a version) and the executable will not be built. Ideally, I would like to be able to tell 'ld' to statically link as much as it can and fail over to the shared object library if a static library cannot be found.

如果我将-static标志传递给 gcc,ld 会出错,说它找不到有问题的库(我认为它正在寻找 .a 版本)并且不会构建可执行文件。理想情况下,我希望能够告诉“ld”尽可能多地静态链接,如果找不到静态库,则故障转移到共享对象库。

In the interium I tried something like gcc -static -lib1 -lib2 -shared -lib3rdparty foo.c -o foo.exein hopes that 'ld' would statically link in lib1 and lib2 but only have a run-time dependence on lib3rdparty. Unfortunatly, this did not work as I intended; instead the -sharedflag overwrote the -staticflag and everything was compiled as shared-objects.

在 interium 中,我尝试了类似的东西gcc -static -lib1 -lib2 -shared -lib3rdparty foo.c -o foo.exe,希望“ld”能够静态链接 lib1 和 lib2,但只对 lib3rdparty 有运行时依赖性。不幸的是,这并没有达到我的预期。相反,该-shared标志覆盖了该-static标志,并且所有内容都被编译为共享对象。

Is statically linking an all-or-nothing deal, or is there some way I can mix and match?

是静态链接一个全有或全无的交易,还是有什么方法可以混合搭配?

回答by Anthony

Looking at this threadyou can see that it can be done. The guys at GNU suggest

查看 此线程,您可以看到它可以完成。GNU 的人建议

gcc foo.c -Wl,-Bstatic -lbar -lbaz -lqux -Wl,-Bdynamic -lcorge -o foo.exe