靜態庫和動態庫的區別:
靜態庫(xxx.a):GCC在編譯生成可執行程序時,從靜態庫中提取必要的目標文件,在可執行程序編譯成功時,同時包含了目標文件,這樣帶來的缺點是當多個可執行程序同時調用一個庫文件時,加載到內存中的庫文件可能存在重復,這是對內存的一個極大的浪費,但是由於編譯時已經把庫文件中需要的目標程序拷貝過來,因此可執行程序初次加載的速度是比動態庫略顯快些。
動態庫(xxxx.so):GCC在編譯生成執行程序時,拷貝到可執行程序中的僅僅是一個庫的地址(可以理解為指針),這樣當多個可執行程序利用同一個動態庫時,加載到內存中的庫文件僅僅需要一份就可以了,這樣大大的保護的珍貴的內存資源,略為不足的是當執行可執行文件時,需要通過地址尋找動態庫文件,這個過程耗費了些許的時間。
下邊是一個靜態庫創建使用的實例:
[root@localhost ~]# cd /gcc/ar/
[root@localhost ar]# mkdir include
[root@localhost ar]# mkdir lib
建立頭文件:mylib.h
[root@localhost ar]# vim include/mylib.h
int func1(int x,int y);
void func2(int x);
建立以下的源文件:main.c、func1.c、func2.c
[root@localhost ar]# vim main.c
#include <stdio.h>
#include "mylib.h"
int main(void)
{
int i;
i = func1(1,2);
func2(i);
return 0;
}
~
[root@localhost ar]# vim func1.c
#include "mylib.h"
int func1(int x,int y)
{
return(x+y);
}
~
[root@localhost ar]# vim func2.c
#include <stdio.h>
#include "mylib.h"
void func2(int x)
{
printf("The result is %d\n",x);
}
~
生成目標文件
[root@localhost ar]# gcc -Wall -O -c func1.c –Linclude
[root@localhost ar]# gcc -Wall -O -c func2.c –Iinclude
[root@localhost ar]# gcc -Wall -O -c main.c –Iinclude
生成庫文件
[root@localhost ar]#cd lib/
[root@localhost lib]# ar cr libethnicity.a ../func1.o ../func2.o
[root@localhost lib]# ar t libethnicity.a
func1.o
func2.o
編譯生成可執行文件(這裡采用三種方式)
1)采用-L library ,-I include方式
[root@localhost ar]# gcc -Wall -O main.o -Llib -lethnicity -o wanyan
[root@localhost ar]# ./wanyan
The result is 3
2)采用添加到系統庫的方式
[root@localhost ar]# cp lib/libethnicity.a /usr/lib
[root@localhost ar]# gcc -Wall -O main.o -lethnicity -o ethnicitybeta
[root@localhost ar]# ./ethnicitybeta
The result is 3
3)修改本地.bash_profile的方式
[root@localhost ar]# export LIBRARY_PATH=/gcc/ar/lib:$LIBRARY_PATH
[root@localhost ar]# gcc -Wall -O main.o -lethnicity -o laji
[root@localhost ar]# ./laji
The result is 3
實驗結束
總結:這個小實驗是對小布老師視頻學習的一個筆記,之所以采用的代碼十分的簡單,是因為這個實驗是為了了解靜態庫建立使用的遠離,最後列出了三種GCC編譯時加載靜態庫的方法,十分的實用。