这里采用显示调用的方法加载动态库
动态库的创建
首先实现hello()函数
// hello.h
#include <iostream>
// modified by extern "C", or occured "segmentation fault"
extern "C" void hello();
- 注意这里一定要extern "C"来修饰需要调用的函数,否则会出现segmentation fault问题
// 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文件
调用
这里显示调用需要用到<dlfcn.h>库,这是一个c库,因此我们要用c的格式来操作
// share.cpp
#include <dlfcn.h>
#include <iostream>
#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