用gcc生成.a的静态库和.so动态库

1.编辑生成例子程序 hello.h、hello.c 和 main.c

创建项目目录

mkdir test1 
cd test1

编辑生成所需要的 3 个文件
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 文件

无论静态库,还是动态库,都是由.o 文件创建的

gcc -c hello.c

用ls命令查看
请添加图片描述

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

静态库文件名的命名规范是以 lib 为前缀,紧接着跟静态库名,扩展名为.a,创建静态库用 ar 命令

ar -crv libmyhello.a hello.o

请添加图片描述

4.在程序中使用静态库

gcc main.c libmyhello.a -o hello
./hello

请添加图片描述

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

动态库文件名命名规范和静态库文件名命名规范类似,也是在动态库名增加前缀 lib,但其 文件扩展名为.so,用 gcc 来创建动态库。

gcc -shared -fPIC -o libmyhello.so hello.o 

注意:-o 不可少
请添加图片描述

6.在程序中使用动态库

用 gcc 命令生成目标文件时指明动态库名进行编译

gcc -o hello main.c -L. -lmyhello

没有libmyhello.so会报错,输入以下

gcc main.c libmyhello.so -o hello

没有报错,但是用./hello会报错
请添加图片描述请添加图片描述
是找不到动态库文件 libmyhello.so。程序在运行时, 会在/usr/lib 和/lib 等目录中查找需要的动态库文件。若找到,则载入动态库,否则将提 示类似上述错误而终止程序运行。我们将文件 libmyhello.so 复制到目录/usr/lib 中,再试试。

mv libmyhello.so /usr/lib
./hello 
Hello everyone!

7.多个文件生成静态库或动态库与目标文件链接

  1. 创建目录
mkdir test2 
cd test2
  1. 编辑生成所需要的 4 个文件
    x2x.c
#include <stdio.h> 
void print1(int arg)
{ printf("A1 print arg:%d\n",arg); 
}

y2y.c

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

xy.h

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

main.c

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

请添加图片描述

  1. 静态库.a 文件的生成与使用
    3.1 生成目标文件
gcc -c x2x.c y2y.c

3.2 生成静态库.a文件

ar -crv libafile.a x2x.0 y2y.o

请添加图片描述
3.3 链接文件,执行文件

gcc main.c libafile.a -o test
./test

请添加图片描述
4. 共享库.so 文件的生成与使用

4.1 生成共享库.so文件

gcc -shared -fPIC -o libsofile.so x2x.0 y2y.o

4.2 使用.so共享库,创建可执行程序
注意:与上面相同,需将生成的动态库文件复制到目录/usr/lib

gcc main.c libsofile.so -o test
./test

请添加图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值