如何修复 C++ error: undefined reference to dlopen

问题:

编译 C++ 应用程序时,你看到以下一个或多个或类似错误消息(完整错误消息日志示例如下所示)

linker_error.log
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'

解决方案

你需要将 dl(动态链接器)库链接到你的可执行文件。手动运行 gcc 时,使用 -ldl 选项,例如:

build.sh
gcc -o myexe main.cpp -ldl

使用 CMake 时,使用

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

完整错误日志示例:

full_error.log
/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'

Check out similar posts by category: C/C++, GCC Errors