本文内容:学习了解在gcc下生成和使用静态库和动态库,并进行比较认识到二者的相同点和不同点。
目录
一、何为静态库与动态库
静态库
在程序编译时会被连接到目标代码中,程序运行不需要静态库的存在。
动态库
在程序编译时不会被连接到目标代码中,而是程序运行时载入的。
两者区别:前者是编译连接的,后者是程序运行载入的。
二、库的生成与使用
(一)准备代码
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;
}
编译得到.o文件
(二)静态库的使用
静态库文件名的命名规范是以 lib 为前缀,紧接着跟静态库名,扩展名为.a。例如:我们将 创建的静态库名为myhello,则静态库文件名就是libmyhello.a。在创建和使用静态库时, 需要注意这点。创建静态库用 ar 命令。在系统提示符下键入以下命令将创建静态库文件libmyhello.a。
(1)创建静态库
静态库文件命名规范:以lib作为前缀,是.a文件
(2)使用静态库
(三)动态库的使用
动态库文件名命名规范和静态库文件名命名规范类似,也是在动态库名增加前缀 lib,但其 文件扩展名为.so。例如:我们将创建的动态库名为myhello,则动态库文件名就是 libmyhello.so。用 gcc 来创建动态库。 在系统提示符下键入以下命令得到动态库文件 libmyhello.so。
(1)创建动态库
创建动态库的工具:gcc
动态库文件命名规范:以lib作为前缀,是.so文件
gcc -shared -fPIC -o libmyhello.so hello.o
shared:表示指定生成动态链接库,不可省略
-fPIC:表示编译为位置独立的代码,不可省略
我们需要用rm先将原有的静态库删掉
(2)使用动态库
gcc -o hello main.c -L. -lmyhello
运行可执行文件hello,会出现错误
问题的解决方法:将libmyhello.so复制到目录/usr/lib中。由于运行时,是在/usr/lib中找库文件的。
mv libmyhello.so /usr/lib
(四)静态库与动态库的比较
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
在执行可执行文件,会报一个错误,可见当静态库和动态库同时存在的时候,程序会优先使用动态库。
三、两组实例
(一)实例一
(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;
}
输入指令mkdir创建文件A,用gedit将各个文件放入其中
(2)静态库
过程如下
(3)动态库
过程如下
(二)实例二
(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));
}
输入指令mkdir创建文件B,用gedit将各个文件放入其中
(2)静态库
过程如下
(3)动态库
过程如下
四、总结
通过使用静态库和动态库,能明显看出二者的不同,区别于有界面的编译运行,能更加真实的了解到计算机真正的过程。