gcc生成静态库和动态库
一、Gcc生成.a和.so库
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 -shared -fPIC -o libmyhello.so hello.o
查看文件夹中是否成功生成
4.使用静态库
使用如下命令生成hello文件
gcc main.c libmyhello.a -o hello
接着输入./hello
运行得到如下结果
5.使用动态库
使用如下命令生成hello文件
gcc main.c libmyhello.so -o hello
接着输入./hello
运行得到如下结果
至此,可以看到有报错信息,这是因为找不到动态库文件 libmyhello.so。程序在运行时, 会在/usr/lib 和/lib 等目录中查找需要的动态库文件。若找到,则载入动态库,否则将提 示类似上述错误而终止程序运行。
我们可以在获得管理员权限后将文件 libmyhello.so 复制到目录/usr/lib 中,就能解决这个问题
获得管理员权限后,使用如下命令移动文件
mv libmyhello.so /usr/lib
再次运行./hello
,就可以完成输出了
二、Linux下.a 与.so 库文件的生成与使用
1.新建一个文件夹,并新建A1.c、A2.c、A.h和test.c文件
- 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 <stdlib.h>
#include "A.h"
int main(){
print1(1);
print2("test");
exit(0); }
2.使用静态库
- 先生成A1.o和A2.o文件
gcc -c A1.c A2.c
- 生成静态库
ar crv libafile.a A1.o A2.o
- 静态库生成执行文件并运行
gcc -o test test.c libafile.a
3.使用动态库
- 生成目标文件
gcc -c -fpic A1.c A2.c
- 生成动态库
gcc -shared *.o -o libsofile.so
- 使用动态库生成可执行文件并运行
gcc -o test test.c libsofile.so
- 至此,同样报错。解决方法与上面的一样。
三、自建函数库.a 与.so 库文件的生成与使用
1.创建x2x.c、x2y.c、x.h和main.c文件
- x2x.c
float x2x(int a,int b)
{
float c=0;
c=a+b;
return c;
}
- x2y.c
float x2y(int a,int b)
{
float c=0;
c=a*b;
return c;
}
- x.h
#ifndef X_H
#define X_H
float x2x(int a,int b);
float x2y(int a,int b);
#endif
- main.c
#include<stdio.h>
#include"x.h"
void main()
{
int a,b;
printf("Input a:");
scanf("%d",&a);
printf("Input b:");
scanf("%d",&b);
printf("a+b=%.2f\n",x2x(a,b));
printf("a*b=%.2f\n",x2y(a,b));
}
2.使用静态库
- 生成目标文件
gcc -c x2x.c x2y.c
- 生成静态库文件
ar crv xy.a x2x.o x2y.o
- 生成可执行文件并运行
gcc -o main mian.c xy.a
3.使用动态库
- 生成目标文件
gcc -c -fpic x2x.c x2y.c
- 生成动态库
gcc -shared *.o -o xy.so
- 生成可执行文件并运行
gcc -o main main.c xy.so
总结
通过本次实验有利于我们掌握使用gcc生成静态和动态库的命令以及理解两者的区别
参考文章
https://blog.csdn.net/weixin_56102526/article/details/120742106?spm=1001.2014.3001.5501
https://blog.csdn.net/qq_45659777/article/details/120624942?spm=1001.2014.3001.5501