用gcc生成静态库和动态库

一、用gcc生成静态库和动态库

1.编辑生成hello.h,hello.c和main.c

hello.h

#ifndef HELLO_H
#define HELLO_H
void hello(const char *name);
#endif//HELLO_H

hello.c

#include<stdio.h>
void hello(const char *name)
{
	printf("Hello %s\n",name);
}

main.c

#include"hello.h"
int main()
{
	hello("everyone");
	return 0;
}

2. 将hello.c编译得到.o文件

在这里插入图片描述

3.由.o文件创建静态库

静态库文件名的命名规范是以 lib 为前缀,紧接着跟静态库名,扩展名为.a。创建静态库用 ar 命令。在系统提示符下键入以下命令将创建静态库文件libmyhello.a。

创建静态库

创建静态库的工具: ar
静态库文件命名规范:以lib作为前缀,是.a文件
在这里插入图片描述

4.在程序中使用静态库

方法一:

gcc -o hello main.c -L. –lmyhello
在这里插入图片描述

方法二:

gcc main.c libmyhello.a -o hello
在这里插入图片描述

方法三:

先生成 main.o :
gcc -c main.c
再生成可执行文件:
gcc -o hello main.o libmyhello.a

在这里插入图片描述

5.由.o文件创建动态库

创建动态库的工具:gcc
动态库文件命名规范:以lib作为前缀,是.so文件

gcc -shared -fPIC -o libmyhello.so hello.o
shared:表示指定生成动态链接库,不可省略
-fPIC:表示编译为位置独立的代码,不可省略

我们需要用rm先将原有的静态库删掉 在这里插入图片描述

6.在程序中使用动态库

gcc -o hello main.c -L. -lmyhello
再运行可执行文件hello,会出现错误
在这里插入图片描述
问题的解决方法:将libmyhello.so复制到目录/usr/lib中。由于运行时,是在/usr/lib中找库文件的。

二、实例使用库

实例一

A1.c

#include<stdio.h>
void print1(int arg)
{
	printf("A1 print arg:%d\n",arg);
}

A2.c

#include<stdio.h>
void print2(char *arg)
{
	printf("A2 printf arg:%s\n",arg);
}

A.h

#ifndef A_H
#define A_H
void print1(int);
void print2(char *);
#endif

test.c

#include<stdio.h>
#include"A.h"
int main()
{
	print1(1);
	print2("test");
	return 0;
}

输入指令mkdir创建文件A,用gedit将各个文件放入其中
在这里插入图片描述

静态库

在这里插入图片描述

动态库

在这里插入图片描述

实例二

代码
sub1.c

float x2x(int a,int b)
{
	float c=0;
	c=a+b;
	return c;
}

sub2.c

float x2y(int a,int b)
{
	float c=0;
	c=a/b;
	return c;
}

sub.h

#ifndef SUB_H
#define SUB_H
float x2x(int a,int b);
float x2y(int a,int b);
#endif

main.c

#include<stdio.h>
#include"sub.h"
void main()
{
	int a,b;
	printf("Please input the value of a:");
	scanf("%d",&a);
	printf("Please input the value of b:");
	scanf("%d",&b);
	printf("a+b=%.2f\n",x2x(a,b));
	printf("a/b=%.2f\n",x2y(a,b));
}

输入指令mkdir创建文件B,用gedit将各个文件放入其中

在这里插入图片描述

静态库

在这里插入图片描述

动态库

在这里插入图片描述
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值