C++ g++ 链接器:如果静态库存在,则强制静态链接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3698321/
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-08-28 13:30:32  来源:igfitidea点击:

g++ linker: force static linking if static library exists?

c++clinkerg++static-libraries

提问by kumar

I've a program which links to many libraries. g++, by default, prefers to link to shared libraries, even if the corresponding archive exists.

我有一个链接到许多图书馆的程序。g++,默认情况下,更喜欢链接到共享库,即使相应的存档存在。

How can I change this preference to prefer static archives over dynamic libraries, if a static archive exists?

如果存在静态存档,如何更改此首选项以更喜欢静态存档而不是动态库?

Note, I used -staticoption, but it tries to find static archive for all libraries which is not what I want.

请注意,我使用了-static选项,但它试图为所有不是我想要的库找到静态存档。

回答by naideflan

g++ -Wl,-Bstatic -lz -lfoo -Wl,-Bdynamic -lbar -Wl,--as-needed

Will link zliband libfooas static, and libbaras dynamic . --as-neededwill drop any unused dynamic library.

将链接zliblibfoo作为静态,并libbar作为动态。--as-needed将删除任何未使用的动态库。

回答by stanthomas

When you only want to statically link one or two libraries with the rest, including system libraries, being dynamic, it is often easier to simply reference the static library by its full name. I.e. rather than use -land -Lto get g++ to resolve a library from what it finds, simpy add the full path to the library as an input. Taking the g++ command above, to link a main.oapplication main program to static libz and libfoo and dynamic libbar and libglib etc. :

当您只想将一两个库与其他库(包括系统库)静态链接时,通常更容易通过其全名简单地引用静态库。即,不是使用-l-L让 g++ 从它找到的内容中解析库,简单地将库的完整路径添加为输入。使用上面的 g++ 命令,将main.o应用程序主程序链接到静态 libz 和 libfoo 以及动态 libbar 和 libglib 等:

    g++ main.o /usr/lib/libz.a /usr/lib/libfoo.a -lbar

Edit 3 Aug 17: I've just tripped across this answerwhich goes into more detail and offers an alternative way (-l:) to specify the library directly.

17 年 8 月 3 日编辑:我刚刚偶然发现了这个答案该答案更详细,并提供了另一种方法 ( -l:) 来直接指定库。