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
g++ linker: force static linking if static library exists?
提问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 -static
option, 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 zlib
and libfoo
as static, and libbar
as dynamic . --as-needed
will drop any unused dynamic library.
将链接zlib
和libfoo
作为静态,并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 -l
and -L
to 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.o
application 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.