这里采用显示调用的方法加载动态库
首先实现hello()函数
// hello.h
#include
// modified by extern "C", or occured "segmentation fault"
extern "C" void hello();
// hello.cpp
#include "./hello.h"
void hello() {
std::cout << "shared1 hello" << std::endl;
}
然后编译出来动态链接库
g++ -fPIC -shared hello.cpp -o hello.so
这里 -fIPC 和 -shared 都是固定格式
此时我们生成了hello.so文件
这里显示调用需要用到
// share.cpp
#include
#include
#define LIB_HELLO_PATH "./hello.so"
typedef void (*Hello)();
int main() {
// get shared lib handle
void *handle = dlopen(LIB_HELLO_PATH, RTLD_LAZY);
if (!handle) {
std::cout << "no handle" << std::endl;
return -1;
}
// use function
Hello hello = (Hello)dlsym(handle, "hello");
(*hello)();
// release shared lib
dlclose(handle);
return 0;
}
然后编译生成可执行文件
g++ share.cpp -ldl -o share
这里 -ldl 也是固定用法 load dynamic lib
参考资料:
https://www.cnblogs.com/ArsenalfanInECNU/p/15210427.html
http://t.zoukankan.com/lcchuguo-p-5164362.html