Reputation: 5110
I wrote a code for which I have a Makefile like this:
CC=gcc
CXX=g++
DEBUG=-g
COMPILER=${CXX}
#INCLUDE= -I Re2/ -I Re2/re2/
#WARN=-Wall
spambin: main.cpp Mail.o trie.o Spambin.o config.o getdns.o
${COMPILER} ${DEBUG} ${WARN} -o spambin main.cpp Mail.o trie.o Spambin.o config.o getdns.o /usr/lib/libre2.so
trie.o: trie.cpp
${COMPILER} ${DEBUG} ${WARN} -c trie.cpp ${INCLUDE}
Mail.o: Mail.cpp
${COMPILER} ${DEBUG} ${WARN} -c Mail.cpp ${INCLUDE}
config.o: config.cpp
${COMPILER} ${DEBUG} ${WARN} -c config.cpp ${INCLUDE}
Spambin.o: Spambin.cpp
${COMPILER} ${DEBUG} ${WARN} -c Spambin.cpp ${INCLUDE}
getdns.o: getdns.c
${CC} ${DEBUG} ${WARN} -c getdns.c ${INCLUDE}
clean:
rm -f *.o
The issue I'm facing is that I want my code to directly pick the /usr/lib/libre2.so. Doing ldd on the final output binary gives:
linux-gate.so.1 => (0x00693000) libre2.so.0 => /usr/lib/libre2.so.0 (0x00159000) libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0x004f4000) libm.so.6 => /lib/libm.so.6 (0x00ce8000) libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x002b8000) libc.so.6 => /lib/libc.so.6 (0x00b83000) libpthread.so.0 => /lib/libpthread.so.0 (0x00d13000) /lib/ld-linux.so.2 (0x00b64000)
But when I move this file to live servers and do ldd on the binary, the result is:
linux-gate.so.1 => (0x0018b000) libre2.so.0 => /usr/local/lib/libre2.so.0 (0x00b89000) libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0x0040f000) libm.so.6 => /lib/libm.so.6 (0x00ad2000) libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x00c5e000) libc.so.6 => /lib/libc.so.6 (0x0096c000) libpthread.so.0 => /lib/libpthread.so.0 (0x00ab9000) /lib/ld-linux.so.2 (0x00949000)
The binary path is /usr/local/lib/libre2.so.0.
Is there any way we can force compiler to pick the .so file from our preferred path?
Upvotes: 3
Views: 2962
Reputation: 6531
Yes, there is a way: you can specify full path to the shared library when linking,e.g.:
libtest2.so
(it is in /projects/tests/test_so
)Let my main program cpp file is: main.cpp
Then:
g++ main.cpp -o test /projects/tests/test_so/libtest2.so
Produces binary test which has embedded absolute path /projects/tests/test_so in it. No matter where you move the test binary it will always look for /projects/tests/test_so/libtest2.so
Alternatively you may look at -rpath switch that you can use with gcc (actually it is a linker switch),e.g:
gcc -Wl,-rpath,'<path-to-lib-directory>'
But this approach may cause your program to look also for other shared libraries in <path-to-lib-directory>
which may not be exactly what you want.
Upvotes: 2