一、說明
類似Windows系統中的動態鏈接庫,Linux中也有相應的共享庫用以支持代碼的復用。Windows中為*.dll,而Linux中為*.so。下面詳細介紹如何創建、使用Linux的共享庫。
二、創建共享庫
在mytestso.c文件中,代碼如下:
- #include <stdio.h>
- #include <stdlib.h>
- int GetMax(int a, int b)
- {
- if (a >= b)
- return a;
- return b;
- }
- int GetInt(char* psztxt)
- {
- if (0 == psztxt)
- return -1;
- return atoi(psztxt);
- }
然后使用下列命令進行編譯:
gcc -fpic -shared mytestso.c -o mytestso.so
-fpic 使輸出的對象模塊是按照可重定位地址方式生成的
編譯成功后,當前目錄下有mytestso.so,此時已成功創建共享庫mytestso.so。
三、使用共享庫
共享庫中的函數可被主程序加載并執行,但是不必編譯時鏈接到主程序的目標文件中。主程序使用共享庫中的函數時,需要事先知道所包含的函數的名稱(字符串),然后根據其名稱獲得該函數的起始地址(函數指針),然后即可使用該函數指針使用該函數。
在mytest.c文件中,代碼如下:
- #include <dlfcn.h>
- #include <stdio.h>
- int main(int argc, char* argv[])
- {
- void* pdlhandle;
- char* pszerror;
- int (*GetMax)(int a, int b);
- int (*GetInt)(char* psztxt);
- int a, b;
- char* psztxt = "1024";
- // open mytestso.so
- pdlhandle = dlopen("./mytestso.so", RTLD_LAZY);
- pszerror = dlerror();
- if (0 != pszerror) {
- printf("%sn", pszerror);
- exit(1);
- }
- // get GetMax func
- GetMax = dlsym(pdlhandle, "GetMax");
- pszerror = dlerror();
- if (0 != pszerror) {
- printf("%sn", pszerror);
- exit(1);
- }
- // get GetInt func
- GetInt = dlsym(pdlhandle, "GetInt");
- pszerror = dlerror();
- if (0 != pszerror) {
- printf("%sn", pszerror);
- exit(1);
- }
- // call fun
- a = 200;
- b = 600;
- printf("max=%dn", GetMax(a, b));
- printf("txt=%dn", GetInt(psztxt));
- // close mytestso.so
- dlclose(pdlhandle);
- }
新聞熱點
疑難解答