==================这是动态库te.cpp文件
#include <stdio.h>
#include <string.h>
//这一句一定要有,这是导出该函数
extern "C" void add();
void add()
{
printf("@hk.%s(%d): This is add function! /n", __FILE__, __LINE__);
}
g++ -fPIC -shared -o ./libte.so ./te.cpp
==================这是调用动态库的main.cpp文件
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dlfcn.h> /* 必须加这个头文件 */
#include <assert.h>
typedef void (*add_t)();
int main(int argc, char *argv[])
{
void *handle = NULL;
add_t add;
handle = dlopen("./libte.so", RTLD_LAZY);
if (handle == NULL)
{
printf("@hk.%s(%d): The share library load fail!/n", __FILE__, __LINE__);
return -1;
}
add = (add_t)dlsym(handle, "add");
if (add == NULL)
{
printf("@hk.%s(%d): Load function symbol fail!/n", __FILE__, __LINE__);
}
add();
dlclose(handle);
return 0;
}
g++ -o main main.cpp -ldl