在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文件名
这样就可以制作和使用静态库文件了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值