首页 > 解决方案 > Does anybody know how to link against `ld` on `WSL`?

问题描述

I'm compiling a test program on clion using windows subsystem for linux WSL. I am using dlopen etc. to load a library at runtime. The error I am getting is:

CMakeFiles/test.dir/test_add.cpp.o: In function `test_test_add_windows_Test::TestBody()':
/mnt/d/ACrossPlatformCppLibrary/test/test_add.cpp:26: undefined reference to `dlopen'
/mnt/d/ACrossPlatformCppLibrary/test/test_add.cpp:28: undefined reference to `dlsym'

Reports seem to suggest that I need to link against ld. However, adding

target_link_libraries(ACrossPlatformCppLibrary "${CMAKE_DL_LIBS}")

Doesn't work, which is no suprise because it looks like "${CMAKE_DL_LIBS}" is empty on windows. So I tried to manually give the path to ld

target_link_libraries(ACrossPlatformCppLibrary "/usr/bin/ld")

Does anybody know how to link against ld on WSL?

update

Thanks to comments and the answer by @squareskittles, I've noticed that the dl binary is not available on the system path. On closer inspection, it doesn't look like the dl binary exists at all in WSL. Here is a cut and paste of the directory I think dl should be in:

$ cd /lib
$ ls
apparmor       hdparm                                libhandle.so.1.0.3  netplan        udev
console-setup  init                                  lsb                 open-iscsi     ufw
cpp            klibc-wBFLvVtxy4xJqEadIBJMa78iJz8.so  modprobe.d          recovery-mode  x86_64-linux-gnu
cryptsetup     **ld-linux.so.2**                         modules             systemd
ebtables       libhandle.so.1                        modules-load.d      terminfo

标签: c++windowscmakewindows-subsystem-for-linuxdynamic-linking

解决方案


I think you are confusing the GNU link library flag -l with the library name dl, which together in the link stage appear as -ldl. If the library is in the system path (of WSL), you should not need the full path to the library either. You can simply put the library name dl in this command:

 target_link_libraries(ACrossPlatformCppLibrary PRIVATE dl)

For what it's worth, the libdl.so library on WSL should be located here if you have the proper packages installed:

/lib/x86_64-linux-gnu/libdl.so.2

推荐阅读