#一、前言
如果有公司需要使用你们产品的一部分功能(通过代码调用这些功能),如果不想提供源代码,那么就可以通过封装成库文件的形式提供给对方使用。本文主要介绍了生成动态库与静态库文件的过程、以及封装和使用库文件的方法。
#二、静态库.a与动态库.so的生成与区别
.o文件 :二进制目标文件,可用于打包成库文件也可以链接生成可执行文件;
c文件编译后链接,生成可执行文件
gcc test1.c test2.c test3.c test_main.c -o test_main
./test_main
1
2
将.o目标文件链接生成可执行文件
gcc -c test1.c test2.c test3.c test_main.c//编译成.o目标文件
gcc test1.o test2.o test3.o test_main.o -o test_main_1//把.o文件链接成可执行文件
./test_main_1
1
2
3
源码test1.h
#include <stdio.h>
void log_1();//函数在.h头文件中声明
1
2
源码test1.c
#include "test1.h"
//函数在.C文件中实现
void log_1(){
printf("This is file test1!\n");
}
1
2
3
4
5
源码test2.h
#include <stdio.h>
void log_2();
1
2
源码test2.c
#include "test2.h"
void log_2(){
printf("This is file test2!\n");
}
1
2
3
4
5
源码test3.h
#include <stdio.h>
void log_3();
1
2
源码test3.c
#include "test3.h"
void log_3(){
printf("This is file test3!\n");
}
1
2
3
4
5
源码test_main.h
#include <stdio.h>
#include "test1.h"//引入头文件
#include "test2.h"
#include "test3.h"
void log_1();//声明test1.h中的函数
void log_2();
void log_3();
1
2
3
4
5
6
7
8
9
源码test_main.c
#include "test_main.h"
int main(int argc, char* argv[]){
log_1();//调用test1.h中的函数
log_2();
log_3();
return 0;
}
1
2
3
4
5
6
7
8
.a文件 :静态库文件,静态库在编译时已经被链接到目标代码中,运行程序不依赖该静态库文件;
优点:将程序使用的函数的机器码复制到最终的可执行文件中,提高了运行速度;如果库函数改变,整个程序需要重新编译
缺点:所有需用到静态库的程序都会被添加静态库的那部分内容,使得可执行代码量相对变多,占用内存和硬盘空间
ar rc libtest.a test1.o test2.o test3.o//把.o文件打包成.a的库文件
gcc test_main.c -L. -ltest -o test_main_a//链接生成可执行文件
./test_main_a//运行测试程序
rm libt