关于静态库和动态库的区别网上已经写了很多了,我就不再赘述,大家可以自行搜索。
这里我主要介绍静态库和动态库在运行时间上的区别。
我看书上写的是静态库比动态库在运行速度上快1%~5%。
然后我写了一段程序test.c
#include<stdio.h>
void writeFile(void){
int i = 0;
for(;i<100000;i++){
FILE *fp;
fp = fopen("test1.txt","w");
fprintf(fp,"hello,world %d ",i);
fclose(fp);
}
}
(简单介绍就不写.h文件了,如果大家习惯.h书写规则,就自己写一个吧。)
然后分别编译成静态库和动态库,编译过程网上都有
再写一个main.c
#include<stdio.h>
#include<time.h>
extern void writeFile(void) //声明writeFile函数
int main(){
clock_t start,stop;
double totle;
start = clock();
writeFile();
stop = clock();
totle = ((double)(stop-start)/CLOCKS_PER_SEC);
printf("%fs \n",totle);
return 0;
}
最后运行编译主程序分别调用静态库和动态库,生成testSta 和 testDyn 的可执行文件。
△记住:main中不要去#include"test.c"或者#include"test.h"否则我们最后加载的都是静态库,不会加载到动态库。
如果我们最后要去看下有没有加载到动态库,可以使用gdb调试。
运行后发现,在差异的时间在linux系统运行程序时间的波动上,基本没什么区别,这也难怪网上基本没有写动态库和静态库在运行时间上的区别。
[root@localhost test1]# ./testSta
8.330000s
[root@localhost test1]# ./testDyn
8.490000s
[root@localhost test1]# ./testSta
8.510000s
[root@localhost test1]# ./testDyn
8.480000s