静态库和共享库(动态库)的制作和使用
静态库的制作和使用
1. 建立如下几个文件夹和文件
include lib main.c src
include文件夹下包含如下文件
func.h
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
int sum(int a, int b); int sub(int a, int b); int mul(int a, int b); int div(int a, int b);
src文件夹下包含如下文件
add.c div.c mul.c sub.c
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include"func.h" int add(int a, int b) { return a + b; }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include"func.h" int div(int a, int b) { return a / b; }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include"func.h" int mul(int a, int b) { return a * b; }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include"func.h" int sub(int a, int b) { return a - b; }
main.c 文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <stdio.h> #include "func.h" int main() { int a = 100; int b = 10; printf("a = %d, b = %d\n", a, b); printf("a + b = %d\n", add(a,b)); printf("a - b = %d\n", sub(a,b)); printf("a * b = %d\n", mul(a,b)); printf("a / b = %d\n", div(a,b)); return 0; }
2. 编译源文件
cd src
gcc *.c -c -I../include
得到:
add.c add.o div.c div.o mul.c mul.o sub.c sub.o
3. 打包 .o 文件生成静态库并将其移入lib文件夹下
ar rcs libMyCalc.a *.o
mv libMyCalc.a ../lib
4. 编译 main.c 文件生成可执行文件 result
//方法1
gcc main.c lib/libMyCalc.a -o result -Iinclude
//方法2
gcc main.c -Iinclude -L lib -l MyCalc -o result
执行 result 得到如下结果
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
a = 100, b = 10 a + b = 110 a - b = 90 a * b = 1000 a / b = 10
共享库的制作和使用
gcc -fPIC -c *.c -I../include gcc -shared -o libMyCalc.so *.o -I../include gcc main.c lib/libMyCalc.so -o result -Iinclude