3

I have created a simple C++ application. I can compile it, and it works fine. But now I need to load the 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:

cd ~/workspace/LinuxGcc/src
g++ LinuxGcc.cpp

And I got a 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 the problem?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
vico
  • 17,051
  • 45
  • 159
  • 315
  • 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
  • The answers are completely missing the *why*. For example, thus limited use in a similar situation with a different library. Or this library could be special in some way. Or where is the library physically located (in case it is missing or in an unexpected location) and what is its actual file name? – Peter Mortensen Nov 06 '22 at 02:06
  • [Part of the why](https://stackoverflow.com/questions/56641768/adding-c-external-library-in-visual-studio-code#comment99890420_56641768). – Peter Mortensen Nov 06 '22 at 02:30

3 Answers3

14

From dlopen(3):

   Link with -ldl.

so

g++ LinuxGcc.cpp -ldl

will be OK.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
petersohn
  • 11,292
  • 13
  • 61
  • 98
1

In case of the Bazel build system, linkopts = ['-ldl'].

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131