首先说明静态库和动态库的区别:缓存
静态库,在连接阶段,会将汇编生成的目标文件.o与引用到的库一块儿连接打包到可执行文件中。函数
动态库,在程序编译时并不会被链接到目标代码中,而是在程序运行是才被载入。spa
静态库会和整个可执行文件打包一块儿,在程序更新的时候,会总体的从新编译打包;而动态库程序,只须要更新动态库便可。code
也就是增量更新比总体更新的优点所在,使得选择动态库。io
在上一节头文件查找中,就有main.cpp引入caculate.h。那么把caculate 编译成动态库,提供main.cpp使用。若是caculate里面的函数内容改变,也须要更新caculate生成的动态库便可。是否是很方便。编译
头文件:
class
caculate.h变量
#include "stdio.h"
int add(int a,int b);
实现:gcc
caculate.cpp打包
#include "caculate.h"
int add(int a,int b){
return a+b;
}
调用文件
main.cpp
#include "caculate.h"
int main(){
int a=5;
int b=7;
int c=add(a,b);
printf("a is %d,and b is %d",a,b);
printf("\n a+b=%d",c);
}
先把caculate.cpp编译成动态库:
1、
gcc -fPIC -c caculate.cpp
生成 caculate.o
2、
gcc -shared -o libcaculate.so caculate.o
生成的libcaculate.so 就是动态共享库了。
使用库:
gcc -o main main.cpp -I./ -L. -lcaculate
生成可执行文件 main
当你执行
./main
你会发现报错:cannot open shared object file: No such file or directory
缘由是没有把动态共享库加到系统库里。
方法两种:
一种,添加到系统库配置中
1、把动态库的路径,加入到/etc/ld.so.conf 文件中。
2、执行
./sbin/ldconfig 把配置加载到缓存。
ok,
执行
./main
成功。
二种,添加到环境变量
export LD_LIBRARY_PATH=/media/zhangshiyu/file/work/gccworkspace:$LD_LIBRARY_PATH
其中 gccworkspace 中直接放生成的libcaculate.so了。
执行
./main
也是成功。
查看环境变量:
echo $LD_LIBRARY_PATH
这是简单的gcc使用。若是复杂的工程,makefile 或者cmake来配置编译会更好。