I’m compiling a c++ program using g++ and ld. I have a .so library I want to be used during linking. However, a library of the same name exists in /usr/local/lib, and ld is choosing that library over the one I’m directly specifying. How can I fix this?
For the examples below, my library file is /my/dir/libfoo.so.0. Things I’ve tried that don’t work:
- my g++ command is
g++ -g -Wall -o my_binary -L/my/dir -lfoo bar.cpp - adding
/my/dirto the beginning or end of my$PATHen` variable - adding
/my/dir/libfoo.so.0as an argument to g++
Add the path to where your new library is to
LD_LIBRARY_PATH(it has slightly different name on Mac …)Your solution should work with using the
-L/my/dir -lfoooptions, at runtime use LD_LIBRARY_PATH to point to the location of your library.Careful with using LD_LIBRARY_PATH – in short (from link):
OR
Use the rpath option via gcc to linker – runtime library search path, will be used
instead of looking in standard dir (gcc option):
This is good for a temporary solution. Linker first searches the LD_LIBRARY_PATH for libraries before looking into standard directories.
If you don’t want to permanently update LD_LIBRARY_PATH you can do it on the fly on command line:
You can check what libraries linker knows about using (example):
And you can check which library your application is using: