Reputation: 91
i have a shared library with some functions stored inside it. i want to Access those functions by calling that library from another program. I have done this earlier in C.
Now i want to do the same using C++. I am pretty new to C++ and any suggestions are very much required. BTW, the shared library is written in C. Is it still possible for me to call this in a C++ program and use all the functions of it. Please help me. An example program would be very very helpful.
i am using ubuntu 14.04 and the compiler is the native g++ that comes along with it.
Upvotes: 9
Views: 12513
Reputation: 6423
Load shared libarary using dlopen, and load given symbol using dlsym. Link with -ldl
.
So given a shared library hello.cpp, compile g++ -shared -fPIC -o libhello.so hello.cpp
#include <cstdio>
extern "C" void hello( const char* text ) {
printf("Hello, %s\n", text);
}
(shared libraries should be named lib*.so[.*]
)
Now calling in main.cpp, compile: g++ -o main main.cpp -ldl
#include <dlfcn.h>
extern "C" typedef void (*hello_t)( const char* text );
int main() {
void* lib = dlopen("./libhello.so", RTLD_LAZY);
hello_t hello = (hello_t)dlsym( lib, "hello" );
hello("World!");
dlclose(lib);
}
Upvotes: 10
Reputation: 1641
You said you already did so in C. Actually C++ is based on C, so you still can do it in the same way you did before.
Usually the following steps are required:
Upvotes: 0