问题
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=namespecAdd the archive or object file specified by
namespecto the list of files to link. This option may be used any number of times. Ifnamespecis of the form:filename, ld will search the library path for a file calledfilename, otherwise it will search the library path for a file calledlibnamespec.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 calledlibnamespec.sobefore searching for one calledlibnamespec.a. (By convention, a .so extension indicates a shared library.) Note that this behavior does not apply to:filename, which always specifies a file calledfilename.
回答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