

动态库制作和使用
mkdir /opt/clearn
cd /opt/clearn
编写库代码add.c和add.h
- [root@localhost clearn]# cat add.c
- #include "add.h"
-
- int add(int x, int y)
- {
- return x + y;
- }
- [root@localhost clearn]# cat add.h
- #ifndef __ADD_H__
- #define __ADD_H__
-
- int add(int x, int y);
-
-
- #endif /*__ADD_H__*/
生成库文件libtest.so,库名称 为 test
gcc -fPIC -c add.c
gcc -shared add.o -o libtest.so
将头文件和库文件发给需要使用的人。源代码千万别给对方。
编写测试代码test.c
- #include
- #include
- #include
-
- #include "add.h"
-
- int main(void)
- {
- int x = 15;
- int y = 3;
- printf("x + y = %d\n", add(x, y));
- return 0;
- }
编译测试代码,需要制定引入的库文件路径、库文件头文件路径、库名称,生成a.out可执行文件
gcc test.c -L. -I. -ltest
然后将库文件拷贝到usr/lib目录下,这个目录是linux存放库文件的标准路径
cp libtest.so /usr/lib
1) 如果共享库文件安装到了/lib或/usr/lib目录下, 那么需执行一下ldconfig命令
ldconfig命令的用途, 主要是在默认搜寻目录(/lib和/usr/lib)以及动态库配置文件/etc/ld.so.conf内所列的目录下, 搜索出可共享的动态链接库(格式如lib*.so*), 进而创建出动态装入程序(ld.so)所需的连接和缓存文件. 缓存文件默认为/etc/ld.so.cache, 此文件保存已排好序的动态链接库名字列表.
ldconfig
然后执行a.out即可。

=================================================
方法二发布库文件,但是一重启就失效了
rm -rf /usr/lib/libtest.so
export LD_LIBRARY_PATH=/opt/clearn

============================================
方法三发布库文件 , 永久生效
vim /etc/profile
添加到末尾
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/clearn
刷新环境变量
source /etc/profile

================================================
方法四发布库文件 , 永久生效
删除方法三环境变量文件中配置的并刷新重启,发现a.out不能执行了。
vim /etc/ld.so.conf
将库文件所在文件夹加入末尾
/opt/clearn

刷新
sudo ldconfig -v
再次执行发现a.out可以了
==========================================================
方法四发布库文件 ,永久生效
目前库文件是放在/opt/clearn目录下,不是在标准库目录/usr/lib或者/lib下,所以可以建立软连接,将实际在/opt/clearn目录下的libtest.so文件映射到/usr/lib/libtest.so,就等于直接将文件拷贝到了/user/lib目录下
ln -s /opt/clearn/libtest.so /usr/lib/libtest.so
ldconfig

重启reboot
再执行a.out依然可以找到库文件

==============================================================