chavalisurya
chavalisurya

Reputation: 91

Calling a shared library from c++

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

Answers (2)

user2622016
user2622016

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

See C++ dlopen mini HOWTO.

Upvotes: 10

Alex
Alex

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:

  • 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 )

Upvotes: 0

Related Questions