Linux c++ error: undefined reference to 'dlopen'
You have to link against libdl, add
-ldl
to your linker options
I was using CMake to compile my project and I've found the same problem.
The solution described here works like a charm, simply add ${CMAKE_DL_LIBS} to the target_link_libraries() call
@Masci is correct, but in case you're using C (and the gcc
compiler) take in account that this doesn't work:
gcc -ldl dlopentest.c
But this does:
gcc dlopentest.c -ldl
Took me a bit to figure out...
this doesn't work:
gcc -ldl dlopentest.c
But this does:
gcc dlopentest.c -ldl
That's one annoying "feature" for sure
I was struggling with it when writing heredoc syntax and found some interesting facts. With CC=Clang
, this works:
$CC -ldl -x c -o app.exe - << EOF
#include <dlfcn.h>
#include <stdio.h>
int main(void)
{
if(dlopen("libc.so.6", RTLD_LAZY | RTLD_GLOBAL))
printf("libc.so.6 loading succeeded\n");
else
printf("libc.so.6 loading failed\n");
return 0;
}
EOF
./app.exe
as well as all of these:
$CC -ldl -x c -o app.exe - << EOF
$CC -x c -ldl -o app.exe - << EOF
$CC -x c -o app.exe -ldl - << EOF
$CC -x c -o app.exe - -ldl << EOF
However, with CC=gcc
, only the last variant works; -ldl
after -
(the stdin argument symbol).