问题
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?
回答1:
dlopen(3):
Link with -ldl.
so
g++ LinuxGcc.cpp -ldl
will be ok.
回答2:
The solution is very simple. Add the -ldl
flag for linking.
回答3:
In case of bazel build system linkopts = ['-ldl']
来源:https://stackoverflow.com/questions/33035712/fixing-undefined-reference-to-dlopen-and-dlcose