如何使用CMake链接库?

时间:2019-11-15 05:40:10

标签: c++ makefile cmake

我正在尝试向使用CMake构建的项目中添加新库,但遇到了麻烦。我正在尝试遵循this。我已经做了一个看起来像这样的测试项目:

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

cmake_test中的CMakeLists.txt看起来像这样:

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})

和liblsl中的CMakeLists.txt看起来像这样:

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

但我不断收到错误No rule to make target '.../liblsl64.lib', needed by 'Tutorial.exe'. Stop. 知道我在做什么错吗? 我在Windows 10上使用mingw-w64 v5.4.0,如果有什么区别。

1 个答案:

答案 0 :(得分:1)

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")

对于Windows使用:

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")

add_library中,您说SHARED是因为您的图书馆是共享图书馆(so / dll),而您说IMPORTED是因为您没有要构建该库,并说GLOBAL,因为您希望它在liblsl之外可见。