9

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.

chavalisurya
  • 91
  • 1
  • 1
  • 5
  • If you [edit] your question to include some more details such as which dev environment (compiler, linker, etc) and possibly which OS, then it *might* be possible to ask a mod (by pressing the [flag] button) to transfer this question to stack overflow. As currently written I suspect it would be closed there very quickly due to lack of detail. – Dan Pichelman Apr 26 '16 at 17:15
  • Definitely OS specific. The way you do this in Windows is completely the way you do it in Linux. – Gort the Robot Apr 26 '16 at 17:31
  • https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=using+shared+library+linux+C%2B%2B – Gort the Robot Apr 26 '16 at 17:32
  • @StevenBurnap thanks for the link man. My thought in asking this question is that, someone would have done this many times already and could provide an example. – chavalisurya Apr 26 '16 at 17:36
  • [How to call a function from a shared library?](http://stackoverflow.com/questions/2538103/how-to-call-a-function-from-a-shared-library) – Thomas Apr 26 '16 at 20:07

2 Answers2

9

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);
}

See C++ dlopen mini HOWTO.

user2622016
  • 6,060
  • 3
  • 32
  • 53
0

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:

  • Use some method provided by the library in your c++ code
  • Figure out which header provides that method, and include it in your .cpp file
  • Compile your C++ code against the headers of the library (compiler flags in the Makefile)
  • Link against the library ( Linker Flags in the Makefile )
Alex
  • 1,602
  • 20
  • 33