Skip to content

Instantly share code, notes, and snippets.

@kwk
Last active August 31, 2024 02:57
Show Gist options
  • Save kwk/3595733 to your computer and use it in GitHub Desktop.
Save kwk/3595733 to your computer and use it in GitHub Desktop.
Fix for "undefined reference to dlopen" in CMake projects

Suppose you get this error with the main.cpp file below:

 Linking CXX executable testlink
 CMakeFiles/testlink.dir/main.cpp.o: In function `main':
 main.cpp:(.text+0x1a): undefined reference to `dlopen'
 main.cpp:(.text+0x2a): undefined reference to `dlclose'
 collect2: ld returned 1 exit status
 make[2]: *** [testlink] Error 1
 make[1]: *** [CMakeFiles/testlink.dir/all] Error 2
 make: *** [all] Error 2

All you need to do is add ${CMAKE_DL_LIBS} to the target_link_libraries() call:

 target_link_libraries(testlink ${CMAKE_DL_LIBS})
project(testlink)
add_executable(testlink main.cpp)
target_link_libraries(testlink)
#include <dlfcn.h>
int main(int argc, char* argv[]) {
void *handle = dlopen("/usr/lib/libmagic.so.1", 0);
dlclose(handle);
return 0;
}
@dktapps
Copy link

dktapps commented May 3, 2019

Thank you sir. 💯

@marisancans
Copy link

Saved my day!

@rqds12
Copy link

rqds12 commented Jul 6, 2019

save the day again

@emabello42
Copy link

Thank you!! You saved my day too :)

@kwk
Copy link
Author

kwk commented Aug 8, 2019

Haha, I'm glad this snippet has helped so many people already. I mean, it is seven years old already :)

@gyzdmgqy
Copy link

Thank you so much this really worked for me.

@ruipacheco
Copy link

Take my knee. Thanks, Buddy

what?

@kamranrad1993
Copy link

kamranrad1993 commented Dec 4, 2020

great.
its a shortcut for :
find_library(dl NAMES dl PATH /usr/lib/x86_64-linux-gnu/libdl.so)
target_link_libraries(${PROJECT_NAME} ${dl})

@FreePhoenix888
Copy link

You saved my time! Thank you!

@PGoski
Copy link

PGoski commented Apr 15, 2022

Saved my time also! Thank you!

@Alireza67
Copy link

Thanks

@taovc
Copy link

taovc commented May 16, 2022

thanks!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

@llyxperf
Copy link

llyxperf commented Oct 5, 2022

thanks!!U saaave my dayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy

@akun-y
Copy link

akun-y commented Oct 22, 2022

thanks!!U saaave my dayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy

@cbldlpl
Copy link

cbldlpl commented Nov 22, 2022

thanks!!U saaave my dayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy

@ep2277
Copy link

ep2277 commented Aug 1, 2023

🚀💥👌. yyyyyyyihaaaaa!

@yhyu13
Copy link

yhyu13 commented Feb 4, 2024

savior for my issue here bombela/backward-cpp#331 with backwardcpp link against libdl

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment