嵌入式——“用gcc生成静态库和动态库.pdf”和“静态库.a与.so库文件的生成与使用.pdf”

一、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 文件创建静态库并使用

ar -crv libmyhello.a hello.o

在这里插入图片描述

使用静态库
gcc main.c libmyhello.a -o hello.o

4.由.o文件创建使用动态库文件

gcc -shared -fPIC -o libmyhello.so hello.o
使用动态库
gcc main.c libmyhello.so -o hello

有错误解决办法:是找不到动态库文件 libmyhello.so。程序在运行时, 会在/usr/lib 和/lib 等目录中查找需要的动态库文件。若找到,则载入动态库,否则将提 示类似上述错误而终止程序运行。我们将文件 libmyhello.so 复制到目录/usr/lib下就可以了

sudo mv libmyhello.so /usr/lib

二、静态库.a与.so库文件的生成与使用.pdf

1.创建文件写入代码

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");
	exit(0);
}

2.静态库.a文件的使用和生成

2.1生成目标文件.o
gcc -c A1.c A2.c
2.2生成静态库.a文件
ar -crv libafile.a A1.o A2.o
2.3使用.a库文件创建可执行程序
gcc -o test test.c libafile.a
./test

在这里插入图片描述

在这里插入图片描述

3.共享库.so文件的生成和使用

3.1生成目标文件.o
gcc -c -fpic A1.c A2.c 
3.2生成共享库.so文件
gcc -shared *.o -o libsofile.so
gcc -o test test.c libsofile.so
./test

在这里插入图片描述

在这里插入图片描述

三、静态库和动态库两者比较

gcc编译得到.o文件 gcc -c hello.c
创建静态库 ar -crv libmyhello.a hello.o
创建动态库 gcc -shared -fPIC -o libmyhello.so hello.o
使用库生成可执行文件 gcc -o hello main.c -L. -lmyhello
执行可执行文件 ./hello,当静态库和动态库同时存在的时候,程序会优先使用动态库。
lo.c
创建静态库 ar -crv libmyhello.a hello.o
创建动态库 gcc -shared -fPIC -o libmyhello.so hello.o
使用库生成可执行文件 gcc -o hello main.c -L. -lmyhello
执行可执行文件 ./hello,当静态库和动态库同时存在的时候,程序会优先使用动态库。
参考:http://t.csdnimg.cn/E4liC

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值