我使用的最簡單的例子,運行一遍基本就熟悉了。
一、動態庫的創建
創建一個hello.c爲源文件的動態庫
#include <stdlib.h>
#include <stdio.h>
void hello(void)
{
printf("Hello World\n");
}
編譯:gcc -shared -fpic -o libhello.so hello.c
-shared :生成一個共享目標文件, 他可以和其他目標文件連接產生可執行文件. 只有部分系統支持該選項。
-fPIC:如果支持這種目標機, 編譯器就輸出位置無關目標碼. 適用於動態連接(dynamic linking),即使分支需要大範圍轉移。
-fpic : 如果支持這種目標機, 編譯器就生成位置無關目標碼. 適用於共享庫(shared library)。
二、動態庫的使用
創建一個名爲test.c的測試文件
#include <stdlib.h>
#include <stdio.h>
#include <stdio.h>
int main(int argc, char **argv)
{
hello();
return 0;
}
編譯前添加下環境變量:export
LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
編譯:gcc -o test test.c -L. -lhello
-L.:表示要連接的庫在當前目錄中。
編譯好後:ldd test
會發現全都能鏈接上,如果不添加環境變量會發現hello這個庫並沒有鏈接上。