函數庫分為靜态庫和動态庫兩種
靜态庫在程式編譯時會被連接配接到目标代碼中,程式運作時将不再需要該靜态庫。
動态庫在程式編譯時并不會被連接配接到目标代碼中,而是在程式運作是才被載入,是以在程式運作時還需要動态庫存在。
示例代碼:
頭檔案 hello.h
#ifndef _HELLO_H
#define _HELLO_H
void hello(void);
#endif
源檔案 hello.c
void hello(void)
{
printf("hello world\n");
}
源檔案 main.c
#include stdio.h>
#include "hello.h"
int main()
hello();
return 0;
靜态庫的制作與使用
靜态庫實際上是o目标檔案的一個歸檔,使用ar工具可以建立靜态庫。
#gcc –c hello.c
#ar cr libhello.a hello.o
使用靜态庫,運作時不依賴靜态庫
#gcc –o main main.c –L. –lhello //生成可執行檔案main
#./main //hello world
#rm libhello.a –rf //移除靜态庫
動态庫的制作與使用
在制作動态庫時,要制定-shared,并可通過-fPIC标志生成位置無關代碼。
-shared
Produce a shared object which can then be linked with othe objects to form an executable. Not all systems support this option. For predictable results, you must also specify the same set of options that were used to generate code (`-fpic', `-fPIC', or model suboptions) when you specify this option.
# gcc -shared -fPIC -o libmyhello.so hello.o
# gcc -o hello main.c -L. -lmyhello
# ./hello
./hello: error while loading shared libraries: libmyhello.so: cannot open shared object file: No such file or directory
因為程式預設在/lib, /usr/lib, LD_LIBRARY_PATH, /etc/ld.so.conf指定的路徑查找庫,是以可以将libhello.so移動到/lib/或/usr/lib下,或将目前目錄加入到環境變量LD_LIBRARY_PATH,或加到配置檔案/etc/ld.so.conf(需要運作ldconfig)。
連結動态庫的程式在運作時需要庫的存在,因其在運作時動态加載庫,進而縮小了可執行檔案的體積,節省了磁盤空間,而且動态庫可被多個使用者程式共享,節省更多的記憶體空間。