//.h
#pragma once
#if __cplusplus
extern "C"{//必须加,因C++会对name进行重新命名 **add**
#endif
int add(const int &numa,const int &numb);
#if __cplusplus
}
#endif
//.cpp
#include"dltest.h"
int myadd(const int &numa,const int &numb)
{
return numa+numb;
}
g++ -fPIC -shared dltest.cpp -o
//.main
#include<dlfcn.h>
#include<iostream>
using namespace std;
typedef int(*Func)(const int&,const int&);
int main()
{
void *handle=dlopen("/data/home/",RTLD_NOW);
char *error;
dlerror();
Func func=(Func)dlsym(handle,"myadd");
if((error=dlerror())!=NULL)
{
cout<<"error:"<<error<<endl;
return -1;
}
int a=1,b=2;
int c=func(a,b);
cout<<c;
dlclose(handle);
}
g++ -g main.cpp -o main -ldl
正常情况下 保证 .so 能被 main 找到,就可以了
但粗心的孩子
可能存在 声明和实现不一致的情况,尤其是 形参 少了或者多了个const参考教程:http:///HOWTO/Program-Library-HOWTO/dl-libraries.html#DL-LIBRARY-EXAMPLE
感谢原作者
















