Program error: ./program: error while loading shared libraries: lib<xxx>.so: cannot open shared object file: No such file or directory

Program error: ./program: error while loading shared libraries: lib<xxx>.so: cannot open shared object file: No such file or directory

(我想让这个问题尽可能通用,所以我会在标题中省略给我出问题的库的名称。)

我有一个项目,对于那个项目我需要一个库 xxx。因此,我下载了该库,使用默认命令 (./configure && make && make install && make clean) 编译 - 安装过程已记录在案 - 并尝试文档中给出的示例是否有效,以查看是否一切都已正确设置。我将代码复制并粘贴到 .c 文件中,并使用以下命令对其进行编译:

gcc -o program program.c -lxxx

并且 gcc 没有报告任何错误。但是,我一运行这个程序,就出现了下面的错误:

 ./program: error while loading shared libraries: lib<xxx>.so: cannot open shared object file: No such file or directory

我想到的第一个解决方案是使用 gcc 选项 -static。它运行良好,程序 运行 正确。但我很失望,因为这意味着程序中的库是 "embedded"(抱歉这里的术语错误:我只是一个学生)。

所以,我在 Stack Overflow 中寻找解决方案:这就是我找到的:error while loading shared libraries: libnsd.so: cannot open shared object file: No such file or directory

库不同,但使用命令

export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH

工作正常。事实上 libxxx.so 在 /usr/local/lib 中(通过使用 ls /usr/local/lib | grep xxx 找到)。线程建议的另一个永久解决方案是在 /etc/ld.so.conf 文件中写入目录名称:

sudo echo "/usr/local/lib" >> /etc/ld.so.conf
sudo ldconfig

这就是棘手的地方:ld.so.conf 文件包含以下行

include /etc/ld.so.conf.d/*.conf

在目录 /etc/ld.so.conf.d 中有一个名为 libc.conf 的文件,其中包含行

/usr/local/lib

我对此感到有点困惑,其中包括;如果它像 C 中的#include 一样工作,我的 /etc/ld.so.conf 文件中应该有 /usr/local/lib。好像不是这样。

/etc/ld.so.conf 仅由 ldconfig 读取,它使用它来填充动态加载程序缓存 /etc/ld.so.cache。如果您将库放入 /usr/local/lib 并且 /usr/local/lib 通过该机制包含在搜索路径中,则只有当您 运行 ldconfig第一。