一.静态库和动态库
1.静态库:
静态库是一组已编译好的对象文件的集合,这些对象文件在编译时会被链接到应用程序中。
当你使用静态库时,库的代码会被完全复制到你的应用程序中,使得应用程序独立运行,不需要外部依赖。
2.动态库:
动态库是一组已编译好的代码和数据,但不会被复制到应用程序中。相反,应用程序在运行时链接到动态库。
多个应用程序可以共享同一个动态库的实例,从而减小磁盘和内存占用。
1.Hello实例使用库
1.编写代码
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.gcc编译得到.o文件
3. 静态库使用
创建静态库
创建静态库的工具:ar
ar -crv libmyhello.a hello.o
程序中使用静态库
gcc -o hello main.c -L. -lmyhello
gcc main.c libmyhello.a -o hello
先生成main.o gcc -c main.c
生成可执行文件 gcc -o hello main.c libmyhello.a
验证静态库的特点
在删掉静态库的情况下,运行可执行文件,发现程序仍旧正常运行,表明静态库跟程序执行没有联系
4.动态库的使用
创建动态库
动态库文件命名规范:以lib作为前缀,是.so文件
gcc -shared -fPIC -o libmyhello.so hello.o
在程序中执行动态库
gcc -o hello main.c -L. -lmyhello或gcc main.c libmyhello.so -o hello
再运行可执行文件hello,会出现错误
问题的解决方法:将libmyhello.so复制到目录/usr/lib中。由于运行时,是在/usr/lib中找库文件的
mv libmyhello.so /usr/lib
2.实例1使用库
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");
return 0;
}
2.程序中使用静态库
3.动态库的使用
gcc -shared -fPIC -o libfile.so A1.o A2.o
gcc -o test test.c libfile.so
3.实例2使用库
1.代码
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));
}
gcc -c sub1.c sub2.c
2.静态库
ar crv libsub.a sub1.o sub2.o
3.动态库
gcc -shared -fPIC libsub.so sub1.o sub2.o
gcc -o main main.c libsub.so
总结
本实验通过三个程序对代码使用静态库和动态库,学习和掌握了生成使用静态库和动态库。在此过程中明白了两者的区别。
参考:https://blog.csdn.net/qq_43279579/article/details/109026927