Linux executable can't find shared library in same folder

拟墨画扇 提交于 2019-12-05 10:46:47

LD_LIBRARY_PATH is a quick ad-hoc hack to specify alternate library loading search paths. A more permanent and cleaner solution is to specify the specific sets of paths in which libraries shall be searched specific for your particular binary. This is called the rpath (Wikipedia article on it: https://en.wikipedia.org/wiki/Rpath). There are a number of "variables" that can be specified in the binary rpath that get substituted. In your case the rpath variable ${ORIGIN} would be the most interesting for you. ${ORIGIN} tells the dynamic linker to look for libraries within the very same directory in which also the binary resides.

The rpath can be set at link time with the -rpath linker option, i.e. when invoked through GCC the option would be -Wl,-rpath='${ORIGIN}', i.e.

gcc -o program_binary -Wl,-rpath='${ORIGIN}' -lSDL2_mixer a.o b.o …

For an existing binary the rpath can be set post-hoc using the chrpath or patchelf tools; it's better to set it at link time proper, though.

Actually nevermind it doesn't work, I had just assumed, that's my bad.

Using the -Wl,-rpath='${ORIGIN}' options literally does not change a thing.

% g++... -Wl,-rpath='${ORIGIN}' -o./bin/nKaruga ...
% cd bin
% ls
libSDL2_mixer-2.0.so.0  nKaruga
% ./nKaruga
./nKaruga: error while loading shared libraries: libSDL2_mixer-2.0.so.0: cannot open shared object file: No such file or directory

Using $ORIGIN instead of ${ORIGIN} gives the same result, as well as using -Wl,-rpath,'${ORIGIN}' and -Wl,-rpath,'$ORIGIN'.

EDIT (don't mind the French) :

% readelf -d ./nKaruga | grep 'RPATH'
 0x000000000000000f (RPATH)              Bibliothèque rpath: [$ORIGIN]

for what it's worth.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!