How to fix C++ error “undefined reference to `dlopen'”

Problem:

When compiling your C++ application, you see one or more of the following or similar error messages (complete error message log example shown below)

dso_dlfcn.c:(.text+0x17): undefined reference to `dlopen'
/usr/bin/ld: dso_dlfcn.c:(.text+0x2a): undefined reference to `dlsym'
/usr/bin/ld: dso_dlfcn.c:(.text+0x35): undefined reference to `dlclose'
dso_dlfcn.c:(.text+0x1b7): undefined reference to `dlsym'
/usr/bin/ld: dso_dlfcn.c:(.text+0x282): undefined reference to `dlerror'
dso_dlfcn.c:(.text+0x2f5): undefined reference to `dlopen'
/usr/bin/ld: dso_dlfcn.c:(.text+0x369): undefined reference to `dlclose'
/usr/bin/ld: dso_dlfcn.c:(.text+0x3a5): undefined reference to `dlerror'
dso_dlfcn.c:(.text+0x466): undefined reference to `dladdr'
/usr/bin/ld: dso_dlfcn.c:(.text+0x4d7): undefined reference to `dlerror'

Solution:

You need to link the dl (dynamic linker) library to your executable. When running gcc manually, use the -ldl option, for example:

gcc -o myexe main.cpp -ldl

When using CMake, use

add_executable(myexe main.cpp)
target_link_libraries(myexe dl)

Full error log example:

/usr/bin/ld: /home/uli/.conan/data/openssl/1.1.1k/_/_/package/6af9cc7cb931c5ad942174fd7838eb655717c709/lib/libcrypto.a(dso_dlfcn.o): in function `dlfcn_globallookup':
dso_dlfcn.c:(.text+0x17): undefined reference to `dlopen'
/usr/bin/ld: dso_dlfcn.c:(.text+0x2a): undefined reference to `dlsym'
/usr/bin/ld: dso_dlfcn.c:(.text+0x35): undefined reference to `dlclose'
/usr/bin/ld: /home/uli/.conan/data/openssl/1.1.1k/_/_/package/6af9cc7cb931c5ad942174fd7838eb655717c709/lib/libcrypto.a(dso_dlfcn.o): in function `dlfcn_bind_func':
dso_dlfcn.c:(.text+0x1b7): undefined reference to `dlsym'
/usr/bin/ld: dso_dlfcn.c:(.text+0x282): undefined reference to `dlerror'
/usr/bin/ld: /home/uli/.conan/data/openssl/1.1.1k/_/_/package/6af9cc7cb931c5ad942174fd7838eb655717c709/lib/libcrypto.a(dso_dlfcn.o): in function `dlfcn_load':
dso_dlfcn.c:(.text+0x2f5): undefined reference to `dlopen'
/usr/bin/ld: dso_dlfcn.c:(.text+0x369): undefined reference to `dlclose'
/usr/bin/ld: dso_dlfcn.c:(.text+0x3a5): undefined reference to `dlerror'
/usr/bin/ld: /home/uli/.conan/data/openssl/1.1.1k/_/_/package/6af9cc7cb931c5ad942174fd7838eb655717c709/lib/libcrypto.a(dso_dlfcn.o): in function `dlfcn_pathbyaddr':
dso_dlfcn.c:(.text+0x466): undefined reference to `dladdr'
/usr/bin/ld: dso_dlfcn.c:(.text+0x4d7): undefined reference to `dlerror'
/usr/bin/ld: /home/uli/.conan/data/openssl/1.1.1k/_/_/package/6af9cc7cb931c5ad942174fd7838eb655717c709/lib/libcrypto.a(dso_dlfcn.o): in function `dlfcn_unload':
dso_dlfcn.c:(.text+0x6b8): undefined reference to `dlclose'