.a结尾的二进制文件,它作为程序的一个模块,在链接期间被组合到程序中。和静态链接库相对的是动态链接库(.so文件),它在程序运行阶段被加载进内存。libxxx.a
xxx 表示库的名字。例如,libc.a、libm.a、libieee.a、libgcc.a 都是 Linux 系统自带的静态库。.o文件:
gcc -c 源文件列表
-c选项表示只编译,不链接,我们已在《GCC -c选项》中进行了讲解。.o文件打包成静态链接库,具体格式为:
ar rcs + 静态库文件的名字 + 目标文件列表
ar 是 Linux 的一个备份压缩命令,它可以将多个文件打包成一个备份文件(也叫归档文件),也可以从备份文件中提取成员文件。ar 命令最常见的用法是将目标文件打包为静态链接库。ar rcs libdemo.a a.o b.o c.o
#include “test.h”
int add(int a,int b)
{
return a + b;
}
sub.c 实现两个数相减,代码展示如下:
#include “test.h”
int sub(int a,int b)
{
return a - b;
}
div.c 实现两个函数相除,代码展示如下:
#include “test.h”
int div(int a,int b)
{
return a / b;
}
还有一个 test.h 头文件,用来声明三个函数,代码展示如下:
#ifndef __TEST_H_ #define __TEST_H_ int add(int a,int b); int sub(int a,int b); int div(int a,int b); #endif
gcc -c *.c
*.c表示所有以.c结尾的文件,也即所有的源文件。执行完该命令,会发现 test 目录中多了三个目标文件,分别是 add.o、sub.o 和 div.o。ar rcs libtest.a *.o
*.o表示所有以.o结尾的文件,也即所有的目标文件。执行完该命令,发现 test 目录中多了一个静态库文件 libtest.a,大功告成。[c.biancheng.net ~]$ cd test [c.biancheng.net test]$ gcc -c *.c [c.biancheng.net test]$ ar rcs libtest.a *.o
|-- include
| `-- test.h
|-- lib
| `-- libtest.a
`-- src
`-- main.c
#include <stdio.h>
#include "test.h" //必须引入头文件
int main(void)
{
int m, n;
printf("Input two numbers: ");
scanf("%d %d", &m, &n);
printf("%d+%d=%d\n", m, n, add(m, n));
printf("%d-%d=%d\n", m, n, sub(m, n));
printf("%d÷%d=%d\n", m, n, div(m, n));
return 0;
}
在编译 main.c 的时候,我们需要使用-I(大写的字母i)选项指明头文件的包含路径,使用-L选项指明静态库的包含路径,使用-l(小写字母L)选项指明静态库的名字。所以,main.c 的完整编译命令为:
gcc src/main.c -I include/ -L lib/ -l test -o math.out
注意,使用-l选项指明静态库的名字时,既不需要lib前缀,也不需要.a后缀,只能写 test,GCC 会自动加上前缀和后缀。./math.out命令就可以运行 math.out 进行数学计算。[c.biancheng.net ~]$ cd math [c.biancheng.net math]$ gcc src/main.c -I include/ -L lib/ -l test -o math.out [c.biancheng.net math]$ ./math.out Input two numbers: 27 9↙ 27+9=36 27-9=18 27÷9=3
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有