相关路径结构
.
├── build
├── caculate.cpp
├── CMakeLists.txt
└── main.cpp
CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
add_compile_options(-fPIC)
add_library(caculate SHARED caculate.cpp)
add_executable(main main.cpp)
target_link_libraries(main dl)
caculate.cpp
extern "C"{
int add(int a,int b)
{
return (a + b);
}
int sub(int a, int b)
{
return (a - b);
}
int mul(int a, int b)
{
return (a * b);
}
int div(int a, int b)
{
return (a / b);
}
}
main.cpp
#include <iostream>
#include <stdlib.h>
#include <dlfcn.h>
typedef int (*CAC_FUNC)(int, int);
int main(){
void *handle;
char *error;
CAC_FUNC cac_func = NULL;
// open the so file
handle = dlopen("./libcaculate.so", RTLD_NOW);
if(!handle){
std::cout << "dlerror() " << std::endl;
exit(-1);
}
dlerror();
*(void **) (&cac_func) = dlsym(handle, "add");
if((error = dlerror()) != NULL){
std::cout << "error" << std::endl;
exit(-1);
}
std::cout << "add: " << (*cac_func)(2, 7) << std::endl;
// close the so
dlclose(handle);
return 0;
}