so檔案為動态連結庫檔案,與windows下的dll檔案相當,linux下系統so檔案一般儲存在/usr/lib中。
下面就說明一下如何生成c++程式的so檔案,以及如何在c++程式中調用該so檔案
==========test.h===========
#ifdef __cplusplus //
extern "C"
{
#endif
class Test{
public:
int hello(int i);
};
int helloT(int j);
#ifdef __cplusplus
}
#endif
==========test.cpp===========
#include"test.h"
#include
using namespace std;
int Test::hello(int i){
if(i>3)
cout<3"<
else
cout<
return 0;
}
int helloT(int j){
Test *t=new Test();
t->hello(j);
return 0;
}
編譯test.cpp檔案
g++ -shared -fpic -lm -ldl -o libtest.so test.cpp
其中,so檔案名必須以lib開頭。編譯具體指令請參考幫助文檔
==========main.cpp===========
#include
#include
#include
#include
using namespace std;
int main() {
void *handle = dlopen("./libtest.so", RTLD_LAZY); //該處的./libtest.so表示so檔案的存放位置,RTLD_LAZY是訓示位
if(!handle) {
printf("open lib error\n");
cout<
return -1;
}
typedef int (*hello)(int);//該處的函數與檔案test.h中需調用的函數保持一緻
hello h= (hello)dlsym(handle, "helloT");// helloT為test.h中調用函數的名字,dlsym傳回一個函數指針
if(!h) {
cout<
dlclose(handle);
return -1;
}
int i;
cin>>i;
(*h)(i);//用函數指針形式調用函數
dlclose(handle);
return 0;
}
編譯main.cpp檔案
g++ main.cpp -ldl -o main
執行./main