Skip to content

Instantly share code, notes, and snippets.

Last active August 1, 2023 19:20
  • Star 20 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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})
add_executable(testlink main.cpp)
#include <dlfcn.h>
int main(int argc, char* argv[]) {
void *handle = dlopen("/usr/lib/", 0);
return 0;
Copy link

kamranrad1993 commented Dec 4, 2020

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

Copy link

You saved my time! Thank you!

Copy link

PGoski commented Apr 15, 2022

Saved my time also! Thank you!

Copy link


Copy link

taovc commented May 16, 2022


Copy link

llyxperf commented Oct 5, 2022

thanks!!U saaave my dayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy

Copy link

akun-y commented Oct 22, 2022

thanks!!U saaave my dayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy

Copy link

cbldlpl commented Nov 22, 2022

thanks!!U saaave my dayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy

Copy link

ep2277 commented Aug 1, 2023

🚀💥👌. yyyyyyyihaaaaa!

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