静态库是一些目标代码的集合.LInux环境下的静态库目标文件一般以.a作为目标文件的扩展名.Linux环境下使用ar命令创建一个静态库.静态库的优点在于使用简单,编译快速.静态库在应用程序生成时,已经编译成为可重定位的目标文件,因此可以不必再编译,节省编译时间,以最短的时间生成可执行程序.
假定有文件static_lib.c,内容如下:
int add(int a , int b) {
return a + b;
}
int sub(int a , int b) {
return a - b;
}
int mul(int a , int b) {
return a * b;
}
int div(int a , int b) {
return a / b;
}
用下面命令编译,生成一个可重定位的目标文件,命令如下:
gcc -c static_lib.c
再使用以下命令创建静态库:
ar rcs static_lib.a static_lib.o
其中ar是创建静态库的命令,rcs是3个参数.r表示把列表中的目标文件加入到静态库中;c表示若指定库不存在,则创建该库文件;s表示更新静态库文件的索引,使之包含新加入的目标文件的内容.
使用静态为时要编写一个头文件static_lib.h内容如下所示:
extern int add(int a, int b);
extern int sub(int a, int b);
extern int mul(int a, int b);
extern int div(int a, int b);
主函数main.c内容如下所示:
#include <stdio.h>
#include "static_lib.h"
int main() {
int a, b;
printf("please input a and b\n");
scanf("%d%d", &a, &b);
printf("the add : %d\n", add(a, b));
printf("the sub : %d\n", sub(a, b));
printf("the mul : %d\n", mul(a, b));
printf("the div : %d\n", div(a, b));
return 0;
}
使用-static选项对静态库进行引用,整个命令如下所示:
gcc main.c -static ./static_lib.a -o app
以上命令生成了可执行文件app,执行以下命令运行:
./app