Peter Bialek
Peter Bialek

Reputation: 25

How do I link a library using CMake?

I'm trying to add a new library to a project built using CMake and am having trouble. I'm trying to follow this. I've made a test project that looks like this:

cmake_test/
    test.cpp
    CMakeLists.txt
    liblsl/
        include/
            lsl_cpp.h
        CMakeLists.txt
        liblsl64.dll
        liblsl64.so
    build/

the CMakeLists.txt in cmake_test looks like this:

cmake_minimum_required(VERSION 3.10)

# set the project name and version
project(Tutorial VERSION 1.0)

# specify the C++ standard
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)

add_executable(Tutorial test.cpp)
add_subdirectory(liblsl)
target_link_libraries(Tutorial PUBLIC ${LSL_LIBRARY})

and the CMakeLists.txt in liblsl looks like this:

find_path(LSL_INCLUDE_DIR lsl_cpp.h)
find_library(LSL_LIBRARY liblsl64)
include_directories(${LSL_INCLUDE_DIR})

But I keep getting the error No rule to make target '.../liblsl64.lib', needed by 'Tutorial.exe'. Stop. Any idea what I'm doing wrong? I'm on Windows 10 using mingw-w64 v5.4.0 if that makes any difference.

Upvotes: 2

Views: 642

Answers (1)

Evg
Evg

Reputation: 26272

CMakeLists.txt in cmake_test:

cmake_minimum_required(VERSION 3.10)
project(Tutorial VERSION 1.0)

add_subdirectory(liblsl)

add_executable(Tutorial test.cpp)
target_compile_features(Tutorial PUBLIC cxx_std_11)
target_link_libraries(Tutorial PUBLIC liblsl)

CMakeLists.txt in liblsl:

add_library(liblsl SHARED IMPORTED GLOBAL)
set_target_properties(liblsl PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/include")
set_target_properties(liblsl PROPERTIES IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/liblsl64.so")

For Windows use:

set_target_properties(liblsl PROPERTIES IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/liblsl64.dll")
set_target_properties(liblsl PROPERTIES IMPORTED_IMPLIB "${CMAKE_CURRENT_SOURCE_DIR}/liblsl64.lib")

In add_library, you say SHARED because your library is a shared one (so/dll), you say IMPORTED because you don't want to build the library, and you say GLOBAL because you want it to be visible outside liblsl.

Upvotes: 2

Related Questions