动态库的加载
静态加载,编译时加载动态库
so.h
#ifndef __SO_H__
#define __SO_H__
#define DLL_PUBLIC __attribute__ ((visibility("default")))
extern "C" {
DLL_PUBLIC void test();
int test2(int _v);
}
class foo
{
private:
int i ;
public:
foo(int i){
i = 3;}
~foo(){};
public:
DLL_PUBLIC void a();
int b(int _v);
};
#endif
so.cpp
#include <stdio.h>
#include "so.h"
void test()
{
printf("test\n");
}
int test2(int _v)
{
return _v*_v;
}
void foo::a()
{
printf("foo::a()\n");
}
int foo::b(int _v)
{
return _v*_v;
}
main.cpp
#include <stdio.h>
#include "so.h"
int main(int argc, char** argv)
{
test();
printf("test2: %d\n", test2(3));
foo f(1);
f.a();
printf("foo::b: %d\n", f.b(2));
return 0;
}
~
编译动态库
g++ -shared so.cpp -fPIC -o libtest.so
main.cpp 加载动态库
g++ main.cpp libtest…so -o main
或者
g++ main.cpp -L ./ test - o main //注意 动态库路径后面要有空格
用nm命令查看动态库的函数和类接口的导出情况
linux 下是默认到处的,可以设置不默认导出
在so.h中定义#define DLL_PUBLIC attribute ((visibility(“default”)))
在需要到处的接口中加上这个宏,编译时动态库时加上这个
g++ -shared -o libtest.so -fPIC -fvisibility=hidden so.cpp
在用nm查看动态库导出情况
发现只导出了用DLL_PUBLIC修饰的函数
测试程序也不能正常编译了
动态库的动态加载
#include <iostream>
#include <stdio.h>
#include <dlfcn.h>
using namespace std;
typedef int (*type_pSo_TLGI)(int ) ;
int main()
{
void *pSo_handle = NULL;
pSo_handle = dlopen("./libtest.so", RTLD_LAZY);
if (!pSo_handle)
{
cout<<"can't open .so"<<endl;
cout<<"dlopen - "<<dlerror()<<endl;
return -1;
}
type_pSo_TLGI pSo_TLGI = (type_pSo_TLGI)dlsym(pSo_handle,"test2");
if (!pSo_TLGI)
{
cout<<"can't cast function"<<endl;
fprintf(stderr, "%s\n", dlerror());
//printf("error %s\n",stderr);
return -1;
}
int i = pSo_TLGI(2);
printf("i %d\n",i);
return 0;
}
注意,g++将目标文件编译成动态库时如果没有用extern "c"修饰函数,g++编译器会在函数的符号上加上一些特殊的符号,在调用dlsym函数时需要用nm命令查看函数的正确符号
T 后面的就是函数的符号
需要这样才能正确加载