Linux系统编程 30 动态库加载错误原因及解决方式
学习笔记
./testdy.out: error while loading shared libraries: libmymath.so: cannot open shared object file: No such file or directory
没有这个文件和目录-》看起来有点扯
错误的原因:
1.链接器
2.动态链接器
两者没有关系
工作的时机不一样
链接器工作于链接阶段,工作的时候,需要 -l -L来支持
动态链接器:工作于程序运行阶段,他工作的时候,需要提供动态库所在的目录位置。
出问题的就是动态链接库。
动态链接器会到固定的地方去找
解决方式就是提供动态库文件的位置
LD_LIBRARY_PATH:服务动态链接器的环境变量
通过环境变量: export LD_LIBRARY_PATH=./lib
将动态库文件放入lib下
$cd lib
$ls
libmymath.a
$rm libmymath.a
$ls
$cd ../
$ls
inc lib resource test.c testdy.out test.out
$cd resource
$ls
add.c add.o div1.c div1.o libmymath.so sub.c sub.o
$mv libmymath.so ../lib
$export LD_LIBRARY_PATH=./lib
$./testdy.out
4+6=10
4-6=-2
4/6=0
环境变量是进程的概念
如果关闭终端后,重新打开终端,
再次执行
$cd test
$ls
dynaticlib file file2 hello hello.c inc staticlib
$cd dynaticlib/
$ls
inc lib resource test.c testdy.out
$./testdy.out
./testdy.out: error while loading shared libraries: libmymath.so: cannot open shared object file: No such file or directory
再次报错。
export LD_LIBRARY_PATH=./lib 是临时生效的。
所以要想永久生效的话,要改配置文件。
$vi ~/.bashrc
添加如下内容
#export LD_LIBRARY_PATH=./
export LD_LIBRARY_PATH=./lib
要使得配置文件起作用
两种方式
方式1.重启终端
方式2.$source ~/.bashrc
$source ~/.bashrc
$^C
$./testdy.out
4+6=10
4-6=-2
4/6=0
lib库文件的路径变化的时候
$ls
inc lib resource test.c testdy.out
$mv lib ../
$ls
inc resource test.c testdy.out
$gcc test.c -o testdy2.out -lmymath -L../lib
test.c:2:20: fatal error: mymath.h: No such file or directory
#include "mymath.h"
^
compilation terminated.
$gcc test.c -o testdy2.out -lmymath -L../lib -I./inc
$./testdy2.out
./testdy2.out: error while loading shared libraries: libmymath.so: cannot open shared object file: No such file or directory
建议:最好使用绝对路径修改环境变量