0

I'm developing a shared library, and on my machine there could be two copies of the same shared library:

  1. the one I installed to the system path: /usr/lib/libmyproject.so
  2. the one I built in my workspace during my development: /home/ziqi.liu/workspace/myproject/build/src/libmyproject.so

So during my development, there're some executables under /home/ziqi.liu/workspace/myproject/build. I want them to use the dynamic library in /home/ziqi.liu/workspace/myproject/build/src/libmyproject.so, however it turns out that they're actually using /usr/lib/libmyproject.so when I use ldd to check the link library.

Is there anyway to specify which dynamic library to use when there are multiple? It would be better if I can specify this for all executables under "this project", since it's very intuitive to link the dynamic library in the same repo I just built, instead of the one installed to the system path.

UPDATED: I've found this post: Where do executables look for shared objects at runtime?

It seems that the dynamic library searching has something to do with the rpath and LD_LIBRARY_PATH environment variables.

What I want is to search for rpath first, and then LD_LIBRARY_PATH.

According to rpath wiki, the rpath is named DT_RPATH, however when I objdump that executable, the only thing I can find is RUNPATH section. I'm not sure if this is a compiler-specific behavior... (I'm running g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0)

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Ziqi Liu
  • 2,931
  • 5
  • 31
  • 64
  • Please shows how you compile currently (makefile/cmake) in [mre]. So you'll get a meaningful answer. – Louis Go Sep 09 '21 at 05:31

2 Answers2

0

Is there anyway to specify which dynamic library to use when there are multiple?

The best way to achieve this is to use the special $ORIGIN tag in the executable.

Assuming you have $D/build/exe and you want that exe to use $D/build/src/libmyproject.so, link your exe with: -rpath '$ORIGIN/src'.

This would allow you to have several build directories (e.g. "release" and "debug" builds), and each binary will pick up the library from its own build tree.

It would also allow you to not install libmyproject.so into /usr/lib at all -- you can keep the binary and the all the required libraries in e.g. /usr/local/$project/{bin/exe,lib/libmyproject.so} and have it all just work(TM).

See also this answer.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362
-1

Just modify LD_LIBRARY_PATH and put your home folder first, like

export LD_LIBRARY_PATH=/home/ziqi.liu/workspace/myproject/build/src/:${LD_LIBRARY_PATH}

Then it should be fine.

Mike Dog
  • 74
  • 1
  • 6