用g++编译生成动态连接库*.so的方法及连接(dlopen() dlsym() dlclose())

论坛 期权论坛 脚本     
匿名网站用户   2020-12-21 07:49   37   0

================================================================
//test_so_file.h

ifndef TEST_SO_FILE_H

define TEST_SO_FILE_H

extern “C”//在c++里这句必须存在,c++编译器会改变函数的名字
{
void TestA();
}

endif

=====================================

//test_so_file.cpp

include

include”test_so_file.h”

using namespace std;
void TestA()
{
cout << endl << “TestA” << endl;
}

==================================

以上代码编译命令生成lib:g++ -shared -o libtest.so test_so_file.cpp

//test.cpp

include

include

include”test_so_file.h”

using namespace std;
int main()
{
//===================================
TestA(); //有头文件的时候可以直接调用
//===================================
void *handle = NULL;
char *error;

handle = dlopen("./libtest.so", RTLD_LAZY);
if (!handle)
{
    cout << "error dlopen file !" << endl;
    return 0;
}
dlerror();

typedef void (*function)();
function f1;

f1 = (function) dlsym(handle, "TestA");
if (error = dlerror()) != NULL)
{
    cout << error << endl;
    return 0;
}
f1();
//==========================================
dlclose(handle);

}
//===================================================
编译命令:g++ -O a.out test.cpp -ldl -L. libtest.so
//===================================================
**运行:
1.首先加入libtest.so路径到系统中,在文件ld.so.conf最后一行加入libtest.so的文件路径即可:
sudo vi /etc/ld.so.conf
2.更新:
sudo /sbin/ldconfig**

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:1136255
帖子:227251
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP