目录
1 .库的概念
函数:某些功能代码的封装,可能通过将函数声明放置头文件当中,给其它文件进行调用,那么封装的函数可见(可以使用代码实现的过程),称为开源。封装的函数不可见(将代码实现的过程进行封装动静态库),称为闭源(不开源)。
linux以.a结尾的是静态库,以.so结尾的为动态库; linux下默认的库路径/lib
静态库:在编译时以函数叠加的方式增加到代码中,使用运行,可脱离库运行。使用静态库生成的可以文件相对较大,内存开销大,但是运行效率高。
动态库:在编译时以链接的方式增加到代码中,当需要库函数时,才调用,使用动态库生成的可以文件相对较小,内存开销小,但是运行效率略低。
2.本文章所需的代码(简化版)
需要的代码共五个:3个.c 和 2个.h,如下:
1.main.c
#include <stdio.h>
#include "add.h"
#include "reduction.h"
int main(void)
{
int a=10, b=5, c=0;
//加法函数
c=add(a, b);
printf("add=%d\n",c);
//减法函数
c=reduction(a, b);
printf("reduction=%d\n",c);
return 0;
}
2.add.c
#include "add.h"
int add(int a, int b)
{
int sum=0;
sum = a + b;
return sum;
}
3.add.h
#ifndef _ADD_H
#define _ADD_H
int add(int a, int b);
#endif
4. reduction.c
#include "reduction.h"
int reduction(int a, int b)
{
int sum=0;
sum = a - b;
return sum;
}
5.reduction.h
#ifndef _REDUCTION_H
#define _REDUCTION_H
int reduction(int a, int b);
#endif
3.静态库的创建和使用
(1)将add.c和reduction.c生成对应的.o文件
gec@ubuntu:~/Desktop/test02$ gcc -c add.c reduction.c
(2) 将.o生成.a(静态库)文件
gec@ubuntu:~/Desktop/test02$ ar -rc libmylib.a add.o reduction.o
静态库命名 : lib+库名(自定义)+.a 比如:libmylib.a
(3)运行
gec@ubuntu:~/Desktop/test02$ gcc main.c -o main libmylib.a
gec@ubuntu:~/Desktop/test02$ ./main
4.动态库的创建和使用
(1)将.c文件生成.so(动态库)文件
动态库命名::lib+库名(自定义)+.so+(版本号) 比如libmylib.so
gec@ubuntu:~/Desktop/test02$ gcc -fpic -shared add.c reduction.c -o libmylib.so
(2)编译main.c
gec@ubuntu:~/Desktop/test02$ gcc main.c -o main libmylib.so
(3)运行
注意:这里是将动态库文件复制到系统默认库路径/lib下面
gec@ubuntu:~/Desktop/test02$ cp libmylib.so /lib
运行:
gec@ubuntu:~/Desktop/test02$ ./main