標籤:lib 參考 連結 之間 tld log title 動態連結程式庫 調用
1.C語言中的連結器
(1)每個 C 語言源檔案被編譯後產生目標檔案,這些目標檔案最終要被連結在一起產生可執行檔案。
(2)連結器的主要作用是把各個模組之間相互引用的部分處理好,使得各個模組之間能夠正確的銜接。
2.靜態連結
由連結器在連結時將庫的內容直接加入到可執行程式中
①編譯靜態庫源碼:gcc –c lib.c –o lib.o
②產生靜態庫檔案:ar –q lib.a lib.o //將 lib.o 與其他檔案打包到 lib.a 中
③使用靜態庫編譯:gcc main.c lib.a –o main.out
3.動態連結
可執行程式在運行時才動態載入庫進行連結 ,庫的內容不會進入可執行程式當中
①編譯動態庫源碼:gcc –shared dlib.c –o dlib.so
②使用動態庫編譯:gcc main.c -ldl –o main.out
4.dlopen、dlsym、dlclose使用動態庫
為了使程式方便擴充,具備通用性,可以採用外掛程式形式。採用非同步事件驅動模型,保證主程式邏輯不變,將各個業務已動態連結程式庫的形式載入進來,這就是所謂的外掛程式。linux提供了載入和處理動態連結程式庫的系統調用,非常方便。
①開啟動態庫:dlopen
②尋找動態庫中的函數並返回調用地址:dlsym
③關閉動態庫:dlclose
dlib.c 庫
char* name(){ return "Dynamic Lib";}int add(int a, int b){ return a + b;}
test.c
#include <stdio.h>#include <dlfcn.h>int main(){ //開啟(載入)動態庫 void* pdlib = dlopen("./dlib.so", RTLD_LAZY); char* (*pname)(); int (*padd)(int, int); if( pdlib != NULL ) { //尋找函數地址 pname = dlsym(pdlib, "name"); padd = dlsym(pdlib, "add"); if( (pname != NULL) && (padd != NULL) ) { printf("Name: %s\n", pname()); printf("Result: %d\n", padd(2, 3)); } //關閉動態庫 dlclose(pdlib); } else { printf("Cannot open lib ...\n"); } return 0;}
gcc -shared dlib.c -o dlib.so
gcc test.c -o test.o -ldl
參考資料:
www.dt4sw.com
http://www.cnblogs.com/5iedu/category/804081.html
-----------自己使用的過程--------------------
動態庫:
[[email protected] src]# cat Makefileall: gcc -w -g -std=c99 -fPIC -shared -I../include/zookeeper -I../inlcude -L../lib/ -lzookeeper_mt -o ecox_rws_helper.so zookeeperhelper.c clusterinfohelper.c gcc -o test main.c ecox_rws_helper.soclean: rm *.so test[[email protected] src]#
靜態庫:
[[email protected] src]# cat Makefile_staticall: gcc -g -std=c99 -I../include/zookeeper -o zookeeperhelper.o -c zookeeperhelper.c -I../include -L../lib -lzookeeper_mt gcc -g -std=c99 -o clusterinfohelper.o -c clusterinfohelper.c -I../include #這裡無法將zookeeper_mt庫合并到這個靜態庫中,因為那是動態庫···,只能在串連代碼時指定動態庫 ar -q ecox_rws_helper.o zookeeperhelper.o clusterinfohelper.o gcc main.c ecox_rws_helper.o -o test_static -L../lib -lzookeeper_mtclean: rm *.o test_static
原始的:
[[email protected] src]# cat Makefile_orgall:ecox_rws_helperecox_rws_helper:zookeeperhelper.o main.o clusterinfohelper.o gcc -g -L../lib -lzookeeper_mt -o [email protected] $^zookeeperhelper.o:zookeeperhelper.c gcc -g -std=c99 -I../include/zookeeper -o [email protected] -c $^clusterinfohelper.o:clusterinfohelper.c gcc -g -c -o [email protected] $^main.o:main.c gcc -g -c -o main.o main.c.PHONY:cleanclean: rm *.o
C語言動態庫和靜態庫的使用及實踐