3

I have created simple c++ application. I can compile it and t works fine. But now I need to load library dynamically and I have added dlfnc.h to my project and added some more code:

#include <iostream>
#include <dlfcn.h>
void *mylib;
int eret;

using namespace std;

int main() {

    mylib = dlopen("mylib.so", RTLD_LOCAL | RTLD_LAZY);
    eret = dlclose(mylib);

    cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
    return 0;
}

Compiling:

myname@ubuntu:~/workspace/LinuxGcc/src$ g++ LinuxGcc.cpp 

And got compilation error:

/tmp/ccxTLiGY.o: In function `main':
LinuxGcc.cpp:(.text+0xf): undefined reference to `dlopen'
LinuxGcc.cpp:(.text+0x25): undefined reference to `dlclose'
collect2: error: ld returned 1 exit status

dlfcn.h exist in /usr/include/

Where is problem?

petersohn
  • 10,832
  • 11
  • 57
  • 93
vico
  • 15,367
  • 39
  • 141
  • 262
  • 2
    You added the `.h`, but you also need to link the library http://stackoverflow.com/questions/6016815/how-to-include-needed-c-library-using-gcc – SingerOfTheFall Oct 09 '15 at 10:21
  • Just define suitable functions and it will link: `extern "C" { void dlopen() {} void dlclose() {} }` Alternative read the [man page](http://man7.org/linux/man-pages/man3/dlopen.3.html) and it will tell you what library(-ies) you need to add ( the latter is probably more work but also more likely to result in a working program). – Dietmar Kühl Oct 09 '15 at 10:29

3 Answers3

14

dlopen(3):

   Link with -ldl.

so

g++ LinuxGcc.cpp -ldl

will be ok.

Zesen Qian
  • 141
  • 1
  • 3
  • This works fine! I have the same project in eclipse. How to tell Eclipse that it must link this lib? – vico Oct 09 '15 at 10:29
  • @vico This is an IDE issue, google for "Eclipse C++ link flags" gives me this: http://stackoverflow.com/questions/8480013/eclipse-c-c-cdt-add-l-option-linking-math-module-gcc-lm – Zesen Qian Oct 10 '15 at 14:37
5

The solution is very simple. Add the -ldl flag for linking.

petersohn
  • 10,832
  • 11
  • 57
  • 93
0

In case of bazel build system linkopts = ['-ldl']