PS:相關知識請自己去看man手冊,這裡只給出一個執行個體,及建立這個執行個體的步驟。
1:建立test.h, test.c檔案
//test.h#ifndef TEST_H_#define TEST_H_#include <stdio.h>void PrintHello();int Add(int a, int b);#endif
//test.cpp#include "test.h"//輸出文本hello, worldvoid Hello(){printf("hello, world\n");}//返回兩個參數的和int Add(int a, int b){return a + b;}
2:將其編譯成動態庫
gcc test.c -shared -fPIC -o libtest.so
3:建立主檔案main.c
//main.c#include <stdio.h>#include <stdlib.h>#include <dlfcn.h>#include <signal.h>#include <errno.h>//輸出錯誤資訊並退出 void error_quit(const char *str) { fprintf(stderr, "%s\n", str); exit(1); } int main(int argc, char *argv []){void *plib;//指向so檔案的指標typedef void (*FUN_HELLO)();typedef int (*FUN_ADD)(int, int);FUN_HELLO funHello = NULL;//函數指標FUN_ADD funAdd = NULL;//開啟so檔案//為了方便示範,我將庫檔案和可執行檔放在同一個目錄下plib = dlopen("./libtest.so", RTLD_NOW | RTLD_GLOBAL);if( NULL == plib )error_quit("Can't open the libtest.so");//載入函數void Hello()funHello = dlsym(plib, "Hello");if( NULL == funHello )error_quit("Can't load function 'Hello'");//載入函數int Add(int a, int b)funAdd = dlsym(plib, "Add");if( NULL == funAdd )error_quit("Can't load function 'Add'");//調用成功載入的函數funHello();printf("5 + 8 = %d\n", funAdd(5, 8));//關閉so檔案dlclose(plib);return 0;}
4:編譯,運行
gcc main.c -o main -ldl./main
完成了,呵呵