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

================================================================
//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**

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值