函數庫分為靜態庫和動態庫兩種

靜態庫在程序編譯時會被連接到目標代碼中,程序運行時將不再需要該靜態庫。
動態庫在程序編譯時並不會被連接到目標代碼中,而是在程序運行是才被載入,因此在程序運行時還需要動態庫存在。

示例代碼:

頭文件  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  //移除靜態庫
#./main   //hello world

動態庫的制作與使用
在制作動態庫時,要制定-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)。
鏈接動態庫的程序在運行時需要庫的存在,因其在運行時動態加載庫,從而縮小了可執行文件的體積,節省了磁盤空間,而且動態庫可被多個用戶程序共享,節省更多的內存空間。
arrow
arrow
    文章標籤
    c++ linux 編程 開發
    全站熱搜

    主要步驟 發表在 痞客邦 留言(0) 人氣()