为什么LD_LIBRARY_PATH是BAD以及加载动态库的正确方法 [英] Why LD_LIBRARY_PATH is BAD and the correct way to load dynamic libraries
问题描述
因此,我有一个与OpenBlas一起运行的程序,我想对其进行编译。链接过程如下:
So, I have a program that runs with OpenBlas and I want to compile it. The linking process looks like this:
gcc -o prog prog.o -O3 -I/opt/OpenBLAS/include -L/opt/OpenBLAS/lib -lopenblas
到目前为止很好。如果删除 -L
选项,则会在链接过程中出现错误
So far so good. If I remove the -L
option, I get an error in the linking process
/usr/bin/ld: cannot find -lopenblas
> -L 所有链接均无错误。但是,当我尝试运行它时,出现以下错误:
With the -L
everything links without errors. However, when I try to run it I get the following error:
./prog: error while loading shared libraries: libopenblas.so.0: cannot open shared object file: No such file or directory
如果我设置了env变量 LD_LIBRARY_PATH
到 / opt / OpenBlas / lib
,我可以运行该程序,但是许多来源如 http://xahlee.info/UnixResource_dir/_/ldpath.html 认为这是一种不好的做法,我可以了解几乎所有的理由。本文中提到的另一种方法(修改ld配置)也被认为是一种不好的做法。最后,您可以在 / usr / lib
中向库添加符号链接。后两种方法的一个大问题是您需要sudo访问。
If I set the env variable LD_LIBRARY_PATH
to /opt/OpenBlas/lib
I can run the program, but many sources like http://xahlee.info/UnixResource_dir/_/ldpath.html consider this to be a bad practice and I can understand almost all the reasoning. The other method mentioned in the article (modify the ld configuration) is also considered to be somewhat a bad practice. Finally, you could just add a symlink to the library in /usr/lib
. A big problem with the last two methods is that you need sudo access.
所以我的问题是如何编译和运行链接到不在默认路径( / usr / lib
),而无需使用 LD_LIBRARY_PATH
和sudo访问。他们在文章中说,您可以只在要查找共享库的二进制文件中写,但我不知道该怎么做( -L
标志不会似乎正在这样做)。如果有人能解释这件事,我将不胜感激,因为我到处都是,而且我很困惑(一些参考文献似乎建议标志-L应该这样做,但我不为我工作)。
So my question is how can I compile and run a program linked to a shared library that is not located in a default path (/usr/lib
) without using LD_LIBRARY_PATH
and sudo access. In the article they say that you can just 'write' in the binary where to look for shared libraries but I do not know how to do that (the -L
flag does not seem to be doing it). I would appreciate if anyone could explain this matter, since I've been looking everywhere and I'm very confused (some references seem to suggest that the flag `-L' should do it but I does not work for me). Thank you in advance.
推荐答案
将路径添加到运行时库搜索路径。
Add the path to the runtime library search path.
gcc -Wl,-rpath=/opt/OpenBlas/lib ...
-L
选项在链接时的作用, -rpath
选项的作用在运行时。
What the -L
option does at link time, the -rpath
option does at run time.
这篇关于为什么LD_LIBRARY_PATH是BAD以及加载动态库的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!