Linux 当存在同名共享库时,如何强制与静态库链接

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

How can I force linking with a static library when a shared library of same name is present

linuxgccg++ld

提问by user550009

Suppose I have a file main.cppwhich uses sin()function which is defined in libmath. Also suppose that we have both libmath.a and libmath.so available in the same directory. Now if I issue the command g++ -o main main.cpp -lmaththe default behaviour of Linux is to link to the shared library libmath.so. I want to know is there a way to force the program to link with the static library libmath.awithout deleting or moving the shared library?

假设我有一个main.cpp使用sin()libmath. 还假设我们在同一目录中有 libmath.a 和 libmath.so 可用。现在,如果我发出命令g++ -o main main.cpp -lmath,Linux 的默认行为是链接到共享库libmath.so。我想知道有没有办法强制程序链接静态库libmath.a而不删除或移动共享库?

回答by nos

You'll need to pass the -static to the linker, but only for particular libraries you want. e.g.:

您需要将 -static 传递给链接器,但仅限于您想要的特定库。例如:

g++ -o main main.cpp -Wl,-Bstatic -lmath -Wl,-Bdynamic

回答by karlphillip

Use this function:

使用这个功能:

g++ -o main main.cpp /path_to/libmath.a

回答by Dmitry Yudakov

If your linker supports -l:<filename>you may use:

如果您的链接器支持,-l:<filename>您可以使用:

g++ -o main main.cpp -l:libmath.a