C++ Linux下的库(静态库与动态库)
库
库就是 一种可执行代码的二进制格式,可以被载入内存执行。
库可分为静态库
和动态库
其中动态库又叫共享库 share
静态库一般以.a
结尾, 动态库一般以 .so
结尾、
但不论是哪一种,都是给调用着提供 变量、函数、类的。
区别
静态库和动态库在实际使用中的区别
静态库: 在程序编译时,静态库提供的所有变量 函数 类 都会链接合成到 一个可执行文件中。
- 好处就是 不再有依赖问题
- 坏处就是 编译后的可执行文件 体积比较大
动态库:也叫共享库,它并不会链接到代码中,而是程序启动运行时被载入、
- 好处就是 编译后的执行文件 体积小
- 坏处就是 必须保证引用的动态库存在,且程序能够找到它,换个机器有依赖问题
静态库使用
创建 test.cpp
#include <stdio.h>
#include <iostream>
using namespace std;
void f_test(int age)
{
cout << "your age is " << age << endl;
printf("age:%d\n",age);
}
使用g++
编译
g++ -c test.cpp # 会生成 test.o
ar rcs libtest.a test.o
- ar 静态函数创建的命令
- rcs 是ar命令的参数
- test.o 就是我们刚刚命令生成的文件
- libtest.a 这里要说一说,lib一般库的格式都会以这3个开头,然后.a是静态库的后缀,test是我们静态库的名字
使用静态库,创建main.cpp
extern void f_test(int age); //声明要使用的函数
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
f_test(99);
cout << "HI" << endl;
return 0;
}
编译
g++ -o main main.cpp -L. -ltest
- -L . 告诉g++
.
当前目录去找库文件 - -ltest 前缀
lib
和 后缀.a
省略, 在当前目录查找libtest
,它首先回去找.so
结尾的动态库,找不到才找到我们的静态库
执行
./main
动态库使用
test.cpp
和 main.cpp
代码不变
#include <stdio.h>
#include <iostream>
using namespace std;
void f_test(int age)
{
cout << "your age is " << age << endl;
printf("age:%d\n",age);
}
extern void f_test(int age); //声明要使用的函数
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
f_test(99);
cout << "HI" << endl;
return 0;
}
执行,生成动态库 libtest.so
g++ test.cpp -fPIC -shared -o libtest.so
生成可执行文件
g++ main.cpp -o main -L. -ltest
执行
./main
将二进制文件可执行文件main
,移出目录,发现执行不了了
./main: error while loading shared libraries: libtest.so: cannot open shared object file: No such file or directory
我们将libtest.so
移动到 系统公共的库目录中 ,如 /lib、/lib64 都可以
然后再次执行,发现又可以了。
还没有评论,来说两句吧...