在linux中生成静态库.a的方法

静态库制作方法:

假定有以下三个目录:
[root@localhost shumeipai]# ls
include lib main main.c src

(1)main.c 的主函数包含以下内容.
[root@localhost shumeipai]# cat main.c
#include <stdio.h>
#include “arithmetic.h”
int main()
{
printf(“加法运算 =%d \n”,sum(10,20));

printf("减法运算 = %d \n ",sub(50,10));

return 0;

}

(2)在include目录下包含一个arithmetic.h
[root@localhost include]# pwd(显示当前位置)
/home/shumeipai/include

arithmetic.h头文件包含以下内容:

#include <stdio.h>
#ifndef ARITHMETIC
#define ARITHMETIC

int sum(int a,int b);
int sub(int a,int b);

#endif

(3) 在src目录下包含一个arithmetic.c
其内容如下:
[root@localhost src]# cat arithmetic.c
#include “arithmetic.h”

int sum(int a,int b)
{
int num=a+b;
return num;
}

int sub(int a,int b)
{
int num =a-b;
return num;
}

第一步:把所有除了main主函数除外的,要编译成静态库的.c文件打包成.o文件
打包命令如下:

在src目录下执行:gcc *.c -c -I …/include
此命令可以在当前目录生成一个.o文件

[root@localhost src]# gcc *.c -c -I …/include
[root@localhost src]# ls
arithmetic.c arithmetic.o

第二步:通过打包命令ar将所有要打包成静态库的.o文件打包到.a静态库文件中

打包命令为:
ar rcs libMytest.a *.o

这样就会在src目录下生成一个.a的静态库,操作如下
root@localhost src]# ar rcs libMytest.a *.o
[root@localhost src]# ls
arithmetic.c arithmetic.o libMytest.a

最后把 libMytest.a文件移动到lib目录下
[root@localhost src]# mv libMytest.a …/lib/

[root@localhost shumeipai]# cd lib/

[root@localhost lib]# ls
libMytest.a

其中:libMytest.a 为自己起名的静态库名称,Mytest为自己起的名

第三步: 如何使用编译好的静态库?

通过gcc编译生成一个自己的可执行程序:myapp

操作如下:
[root@localhost shumeipai]# ls
include lib main.c src
[root@localhost shumeipai]# gcc main.c lib/libMytest.a -o myapp -Iinclude
[root@localhost shumeipai]# ls
include lib main.c myapp src

备注:如果找不到头文件,则可以通过-I 指定头文件的位置。

nm 命令可以查看静态库中包含的其他.o文件名
这样就可以制作和使用静态库文件了。

猜你喜欢

转载自blog.csdn.net/weixin_44881103/article/details/110954850