Search code examples
ccmakelinkerclion

CMakeLists reports error: ld:cannot find -l


Here is my CMakeLists.txt:

cmake_minimum_required(VERSION 3.14)

project(testlib C)

set(CMAKE_C_STANDARD 99)


include_directories(/usr/local/include/)
find_library(iconv_lib iconv)
add_executable(testlib  library.c)
target_link_libraries(testlib libiconv.a)

In this folder /usr/local/include/ are the files:

iconv.h  localcharset.h

The CMake reports the error:

====================[ Build | testlib | Debug ]=================================
D:\.CLion2019.2\system\cygwin_cmake\bin\cmake.exe --build /cygdrive/d/project/c/testlib/cmake-build-debug --target testlib -- -j 4
Scanning dependencies of target testlib
[ 50%] Building C object CMakeFiles/testlib.dir/library.c.o
[100%] Linking C executable testlib.exe
/usr/lib/gcc/x86_64-pc-cygwin/7.4.0/../../../../x86_64-pc-cygwin/bin/ld: cannot find -liconv
collect2: error: ld returned 1 exit status
make[3]: *** [CMakeFiles/testlib.dir/build.make:84: testlib.exe] Error 1
make[2]: *** [CMakeFiles/Makefile2:76: CMakeFiles/testlib.dir/all] Error 2
make[1]: *** [CMakeFiles/Makefile2:83: CMakeFiles/testlib.dir/rule] Error 2
make: *** [Makefile:118: testlib] Error 2

Solution

  • It seems like you are not using the library located by find_library(), if it is actually found. If the library is not found, you can add search paths to tell CMake where to find this library:

    find_library(iconv_lib 
        NAMES iconv
        PATHS /path/containing/your/iconv/lib
    )
    

    Finally, use the iconv_lib variable you defined when calling target_link_libraries(), like this:

    target_link_libraries(testlib PUBLIC ${iconv_lib})