I want to load my own dynamic link library for C++, here is my test code:
add.cpp
#include <vector>
using namespace std;
int add(int c)
{
vector<int> v;
int i;
int sum = 0;
for (i = 0; i < c; i++)
{
sum = sum + i;
}
return sum;
}
I execute the command as below to build the add.so
:
g++ -fPIC -shared add.cpp -o add.so
Then I try to link it to my C++ project dynamically with dlopen
:
main.cpp
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
typedef int (*add_func_ptr)(int);
int main(int argc, char **argv)
{
void *handle;
double (*cosine)(double);
char *error;
handle = dlopen("./add.so", RTLD_LAZY);
if (!handle)
{
fputs(dlerror(), stderr);
exit(1);
}
add_func_ptr addfun;
addfun = (add_func_ptr)dlsym(handle, "add");
if ((error = dlerror()) != NULL)
{
fputs(error, stderr);
exit(1);
}
printf("%d\n", (*addfun)(2));
dlclose(handle);
}
Lastly, I compile it:
g++ main.cpp -ldl -o main
However, when I execute ./main
, I always get the error: symbol not found
.
There is a similar question, but the answer could not solve my problem. I know the issue may be caused by the name mangling in C++ but I don't know how to solve it, I want to use std::vector
in the dynamic link, so I need to use C++ instead of c to build .so file.