编译动态库
g++ -fpic -shared libFun.cpp -o libFun.so//-fpic表示与位置无关,-shared表示是一个共享的库文件
g++ main.cpp -o main -ldl//ldl是为了在主函数中使用dlopen等函数
简单动态库编写
//libFun.h文件
#pragam once
extern "C" void sayHello();/*加入extern "C"的原因是C++中存在重载,编译后的函数名会发生改变,导致找不到函数;
extern "C"高数编译器按C语言方式编译(C语言不存在重载),就不会发生函数名的改变。*/
//libFun.cpp文件
#include<iostream>
#include "libFun.h"
using namespace std;
void sayHello()
{
cout << "hello!!!" << endl;
}
//main.cpp文件
#include<dlfnc.h>
#include<iostream>
#include "libFun.h"
using namespace std;
int main()
{
void *handle = dlopen("./libFun.so", RTLD_LAZY);//把动态库文件加载进内存,并返回这块内存的地址
if(handle == 0)
{
cout << "dlopen error" <<endl;
return 0;
}
typedef void (*fun)();//定义一个函数指针
fun f = (fun)dlsym(handle, "sayHello");//加载动态库文件中的sayHello()函数
if(f == 0)
{
cout << "dlsym error" << endl;
cout << dlerror() << endl;
return 0;
}
(*f1)();//调用函数
dlclose();
}
//编译步骤
//首先生成动态库
g++ -fpic -shared libFun.cpp -o libFun.so
//生成执行文件
g++ main.cpp -o main -ldl
//运行
./main
#include<dlfcn.h>
void *dlopen(const char *file, int mode);
/*参数
file:动态链接库的文件名,包括路径信息
mode:动态链接库的使用方式,这里介绍两种,RTLD_LAZY,表示在调用dlopen时并不把函数立即加入程序,等到调用某个函数时才加入;
//RTLD_NOW,表示立即把动态库中的所有函数在dlopen执行完之前就加入程序,如果某个函数加入失败,dlopen就会执行出错。
返回值:引用动态链接库的句柄;出错返回NULL
*/
#include<dlfcn.h>
void *dlsym(void *handle, const char *FuncName);
/*参数
handle:dlopen的返回值
FuncName:动态链接库中的函数名
返回值:FuncName函数被加载后,在进程地址空间中的地址;出错返回NULL*/
#include<dlfcn.h>
char *dlerror();
/*返回值
当dlopen、dlsym等函数出错时,dlerror返回字符串说明这些函数出错的原因*/
#include<dlfcn.h>
int dlclose(void *handle);
/*参数
handle:dlopen的返回值*/