How to force ld to use a static lib instead of shared lib?

一笑奈何 提交于 2019-12-23 01:53:23

问题


I am trying to build by source using the static version of the test library. I have both libtest.a and libtest.so available, so I am using the "-static" option. However, It looks like the gcc linker is also trying to search for static version the standard math library. Any idea what option I can use to link the shared versions of the standard libraries?

g++ -static main.cpp -o a.out -L. -ltest

Error:

/usr/bin/ld: cannot find -lm

回答1:


If you want to force the linker to use the static version of a particular library you can use the :filename to force a particular library instead of just giving the linker a 'base' library name and letting it use the first one it finds:

g++ main.cpp -o a.out -l:./libtest.a

From http://sourceware.org/binutils/docs-2.23.1/ld/Options.html:

-l namespec
--library=namespec

Add the archive or object file specified by namespec to the list of files to link. This option may be used any number of times. If namespec is of the form :filename, ld will search the library path for a file called filename, otherwise it will search the library path for a file called libnamespec.a.

On systems which support shared libraries, ld may also search for files other than libnamespec.a. Specifically, on ELF and SunOS systems, ld will search a directory for a library called libnamespec.so before searching for one called libnamespec.a. (By convention, a .so extension indicates a shared library.) Note that this behavior does not apply to :filename, which always specifies a file called filename.




回答2:


I've never used Michael's suggestion, but I will be tucking it away for future use.

The technique I use to fully control library linking is to avoid -L, l, -Bstatic and -Bdynamic altogether by fully specifying the library I want to use. The command would look similar to:

g++ main.cpp -o a.out /usr/local/lib/test.a

or

g++ main.cpp -o a.out /usr/local/lib/test.so

or

g++ main.cpp -o a.out /usr/local/lib/test.so.1.0.0


来源:https://stackoverflow.com/questions/14494158/how-to-force-ld-to-use-a-static-lib-instead-of-shared-lib

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!