創建靜態庫
1.首先將源文件編譯為目標文件
gcc -c calc_mean.c -o calc_mean.o
2.使用ar命令將目標文件打包成靜態庫
ar? rcs libmean.a? ? ? calc_mean.o
關于ar
? ? ar,Linux系統的一個備份壓縮命令,用于創建、修改備存文件(archive),或從備存文件中提取成員文件。ar命令最常見的用法是將【目標文件】打包為【靜態鏈接庫】。
例如:ar rcs libutil.a algorithm.o converter.o processor.o?
三個常用的選項參數:
r ? ?把目標文件加入到庫中,若已經存在則替換掉原來的目標文件
c ? ?若庫不存在,則新建庫
s ? ?寫入一個目標文件索引到庫中,或者更新一個存在的目標文件索引
[注意:靜態鏈接庫的名稱必須以lib開頭,并以.a為后綴]
創建共享庫
1.首先也是將源文件編譯成目標文件,只是使用-fPIC參數
gcc -c -fPIC calc_mean.c -o calc_mean.o
2.將目標文件鏈接成共享庫
gcc -shared -Wl,-soname,libmean.so.1 -o libmean.so.1.0.1? calc_mean.o
關于gcc的一些參數
-fPIC? ? Position independant code, needed for shared libraries. (I am a bit in the dark what exactly the difference between -fpic and -fPIC is. It seems that -fPIC works always while -fpic produces smaller object files.)
-Wl,option ? ?Pass option as an option to the linker. If option contains commas, it is split into multiple options at the commas. That is, the commas are replaced with spaces.
-shared ? ? ? ? ?This is actually an option to the linker, not the compiler.
庫文件的編譯使用
1.靜態庫的調用
gcc -o test main.c -I頭文件的路徑 -L庫文件的路進 -ltest
如果把頭文件和庫文件復制到gcc默認的頭文件目錄/usr/include和/usr/lib里面,那么編譯程序就跟標準庫函數調用一模一樣了
gcc -o test main.c -ltest
2.動態庫的調用
$ gcc main.c libtest.so (直接指定與 libmylib.so 連結)
或用
$ gcc main.c -L. -ltest (linker 會在當前目錄下搜尋 libtest.so 來進行連結)
如果目錄下同時有 static 與 shared library 的話,會以 shared 為主。
使用 -static 參數可以避免使用 shared 連結。
$ gcc main.c -static -L. -ltest