cmake - Header 找不到共享库文件

cmake - Header files of shared library not found

我正在制作一个自定义库,我希望用户可以安装它。但是,当我尝试在 cmake 可执行文件中使用我自己的库时,出现构建错误,指出找不到库 headers。

图书馆CMakeLists.txt:

cmake_minimum_required(VERSION 3.16)
project(mylibrary)

include(GNUInstallDirs)

set(CMAKE_CXX_STANDARD 14)

# Register a library - This will created lib[xxx].so
add_library(mylibrary SHARED src/library.cpp)

configure_file(mylibrary.pc.in mylibrary.pc @ONLY)

# List the /include directory
target_include_directories(mylibrary PUBLIC
        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>  
        $<INSTALL_INTERFACE:include>)

install(TARGETS mylibrary
        EXPORT mylibraryConfig
        LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR})

export(TARGETS mylibrary
        FILE "${CMAKE_CURRENT_BINARY_DIR}/mylibraryConfig.cmake")

install(EXPORT mylibraryConfig
        DESTINATION "${CMAKE_INSTALL_LIBDIR}/mylibrary/cmake"
        NAMESPACE mylibraryConfig::)

install(
        DIRECTORY include
        DESTINATION ${CMAKE_INSTALL_PREFIX})

install(FILES ${CMAKE_BINARY_DIR}/mylibrary.pc
    DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig)

我成功构建和安装的是:

$ cmake .. -DCMAKE_INSTALL_PREFIX=~/libraries/local  # Use non-standard destination
$ make && make install

可执行文件CMakeLists.txt:

cmake_minimum_required(VERSION 3.16)
project(myexecutable)

set(CMAKE_CXX_STANDARD 14)

find_package(mylibrary REQUIRED)

add_executable(myexecutable src/main.cpp)

target_link_libraries(myexecutable PUBLIC mylibrary)

target_include_directories(myexecutable PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)

我可以为这个项目准备cmake:

$ cmake .. -DCMAKE_PREFIX_PATH=~/libraries/local # Use non-standard location

但是,构建失败:

$ make
fatal error: mylibrary/library.h: No such file or directory
    2 | #include <mylibrary/library.h>

据我所知,库(二进制文件和 headers)的位置嵌入在已安装的软件包中。通过 find_package() 检索到的信息,为什么它在这里不起作用?

类似问题:

当共享库目标在配置文件中命名空间时,您需要在使用 find_package 时在下游包中使用全名引用它,即您需要使用

target_link_libraries(myexecutable PUBLIC mylibraryConfig::mylibrary)

或者,通过替换

从安装中删除命名空间
install(EXPORT mylibraryConfig
        DESTINATION "${CMAKE_INSTALL_LIBDIR}/mylibrary/cmake"
        NAMESPACE mylibraryConfig::)

...与:

install(EXPORT mylibraryConfig
        DESTINATION "${CMAKE_INSTALL_LIBDIR}/mylibrary/cmake")