Run-time linking to dynamic libraries not on LD_LIBRARY_PATH

萝らか妹 提交于 2021-02-04 16:32:29

问题


I'm trying to link a project of mine to a particular set of custom-compiled libraries placed on the project's base directory [proj_dir]/lib - not on any of the system's /lib, /usr/lib or /usr/local/lib - to avoid conficts with the installed stock versions of those same libraries.

I'm able to compile the project by passing the library path with the -L flag, but I get error while loading shared libraries libXXX.so: cannot open shared object file: No such file or directory when I run the compiled binary, and ldd tells me it can't find those particular libs.

On the other hand, I am able to run it without issue if I pass LD_LIBRARY_PATH=[proj_dir]/lib to the executable. Still, is there a way to link those libraries implicitly, without having to manually set the LD_LIBRARY_PATH at runtime?


回答1:


You can either

  1. Write a wrapper script to always include LD_LIBRARY_PATH before calling the actual program (more flexible).
  2. Add -Wl,-rpath=<directory> to your linker options to add a directory to the runtime library search path. So assuming you have a libfoo.so and your program and DSO should lie in the same directory, your compilation command could look like this: gcc -o myprogam main.c -L. -lfoo -Wl,-rpath='$ORIGIN'.

Update: As correctly noted by Maxim, setting -rpath=. is dangerous and should be avoided.

For -Wl,, see the gcc manpage and for -rpath see the ld manpage.



来源:https://stackoverflow.com/questions/50762540/run-time-linking-to-dynamic-libraries-not-on-ld-library-path

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