Rajat
Rajat

Reputation: 487

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

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

Upvotes: 3

Views: 4703

Answers (2)

jww
jww

Reputation: 102225

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

Upvotes: 0

Michael Burr
Michael Burr

Reputation: 340188

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.

Upvotes: 9

Related Questions