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