一、用gcc生成静态库和动态库
函数库由一些公用函数制成,分为静态库和动态库两种。
静态库:在程序编译时会被连接到目标代码中,程序运行时将不再需要此静态库。
动态库:在程序编译时不会被连接到目标代码中,而是在程序运行时被载入,程序运行时仍需要此动态库存在。
案例一
(一)创建案例程序
创建目录文件并用vim编辑生成所需文件
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;
}
(二) gcc编译hello.c文件得到.o文件
可用ls命令查看文件。
(三)创建静态库
使用 ar 命令 创建
静态库文件名以lib为前缀,紧接着跟静态库名,扩展名为.a。
(四)使用静态库
删除此静态库后程序依旧能运行。
(五)创建并使用动态库
此处运行出错是因为程序在运行时,会在/usr/lib目录中查找动态库文件。
我们需要将文件 libmyhello.so 复制到目录/usr/lib 中,复制后,程序成功运行。
(六)探究
若静态库和动态库同时存在,gcc会使用哪个库文件?
先删除多余文件,回复程序刚创建的状态。
再次创建静态库和动态库。
运行程序发现出错,证明gcc优先使用动态库。
案例二
(一)创建案例程序
创建目录文件并用vim编辑生成所需文件
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);
}
(二)生成静态库 .a 文件
运行程序
(三)生成动态库文件
出错后和案例一致处理
案例三
(一)代码文件
main1.c
#include "sub1.c"
#include "sub2.c"
#include "stdio.h"
void main()
{
int a=2, b=1;
printf("a/b=%.2f\n",x2x(a, b));
printf("a+b=%.2f\n",x2y(a, b));
}
sub1.c
#include "stdio.h"
float x2x(int a, int b)
{
float c;
c = a/b;
return c;
}
sub2.c
#include "stdio.h"
float x2y(int x, int y)
{
float z;
z = x+y;
return z;
}
(二)gcc编译得到.o文件
(三)使用ar命令创建静态库
(四)使用静态库 运行程序
(五)创建并运行动态库
(六)静态库和动态库文件比较
静态库
动态库
由图可知,静态库文件明显比动态库文件要小。
总结
在两个案例的练习下,能初步使用静态库和动态库,了解了两者之间的差别,实验过程较为顺利,通过网络能较快的解决其中的问题,但想要完全熟练使用还需要更多的练习和努力。