Search code examples
cmakefilecmakecygwin

Using cmake with a shared (dynamic) library


I'm trying to use a simple shared library that I made with a file that just contains a main method. I first ran cmake . which worked fine and didn't return any errors.

Then I ran make but got this error:

$ make
Scanning dependencies of target myprog
[ 50%] Building C object CMakeFiles/myprog.dir/main.c.o
[100%] Linking C executable myprog.exe
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: cannot find -lhello-user
collect2: error: ld returned 1 exit status
clang-3.8: error: linker (via gcc) command failed with exit code 1 (use -v to see invocation)
make[2]: *** [CMakeFiles/myprog.dir/build.make:95: myprog.exe] Error 1
make[1]: *** [CMakeFiles/Makefile2:68: CMakeFiles/myprog.dir/all] Error 2
make: *** [Makefile:84: all] Error 2

The CMakeLists.txt file

cmake_minimum_required(VERSION 2.8.8)
project(LIB_EXAMPLE)
set(CMAKE_C_COMPILER clang)
add_executable(myprog main.c)
target_link_libraries(myprog hello-user)

The library exists inside of /usr/local/lib/ as libhello-user.dll.a

Note: Im using Cygwin for cmake and make


Solution

  • Turning my comment into an answer

    See CMake/Tutorials/Exporting and Importing Targets.

    You either have:

    • to name a full path for the library
      • CMake is not searching for it automatically
      • you would have to add something like find_library(_lib_path NAMES hello-user)
    • or - better - put those into an IMPORTED target

      cmake_minimum_required(VERSION 2.8.8)
      project(LIB_EXAMPLE)
      
      add_library(hello-user SHARED IMPORTED GLOBAL)
      set_target_properties(
          hello-user 
          PROPERTIES 
              IMPORTED_LOCATION /usr/local/lib/libhello-user.dll
              IMPORTED_IMPLIB   /usr/local/lib/libhello-user.dll.a
      )    
      
      add_executable(myprog main.c)
      target_link_libraries(myprog hello-user)