【问题标题】:Requiring exported CMake targets within the exporting build tree在导出构建树中需要导出的 CMake 目标
【发布时间】:2014-07-10 09:46:27
【问题描述】:

我有一个 CMake 项目 Foobar,其中包含一个子目录 examples,它也可以用作独立的 CMake 构建。为此,此子目录执行find_package(Foobar) 并使用导出的目标。 Foobar 提供 FoobarConfig.cmakeFoobarConfigVersion.cmakeFoobarExports.cmake,并且可以在没有 FindModule 的情况下使用。

代码大致如下:

### Top-Level CMakeLists.txt ###
cmake_minimum_required(VERSION 3.0.0)
project(Foobar)

add_library(X SHARED ${my_sources})
install(TARGETS X EXPORT FoobarExports
  LIBRARY DESTINATION ${my_install_destination})
install(EXPORT FoobarExports DESTINATION ${my_install_destination})
# Create the FoobarExports.cmake for the local build tree
export(EXPORT FoobarExports) # the problematic command

# Setup FoobarConfig.cmake etc
# FoobarConfig.cmake includes FoobarExports.cmake
# ...

# Force find_package to FOOBAR_DIR
option(BUILD_EXAMPLES "Build examples" ON)
if(BUILD_EXAMPLES)
  set(FOOBAR_DIR "${CMAKE_BINARY_DIR}")
  add_subdirectory(examples)
endif()

### examples/CMakeLists.txt ###
cmake_minimum_required(VERSION 3.0.0)
project(FoobarExamples)
# Uses FOOBAR_DIR set above
find_package(Foobar NO_MODULE REQUIRED)

add_executable(my_exe ${some_sources})
# Use X from Foobar
target_link_library(my_exe X)

问题在于export(EXPORT FoobarExports) 只会在生成时间结束时创建FoobarExports.cmake 文件,以确保它具有完整的FoobarExports 导出集。

所以这会失败:

cmake . -DBUILD_EXAMPLES=ON
# Error: FoobarExports.cmake not found

然而,有效的是:

cmake .
cmake . -DBUILD_EXAMPLES=ON # rerun cmake with changed cache variable

如果尚未创建文件,我如何在调用 export 时强制写入 FoobarExports.cmake 文件或强制 CMake 运行两次?

【问题讨论】:

    标签: cmake build-system


    【解决方案1】:

    如果您将项目构建为子项目,则无需查找任何内容。只需检查 目标存在,如果不存在,请尝试找到它。类似的东西:

    ### examples/CMakeLists.txt ###
    cmake_minimum_required(VERSION 3.0.0)
    project(FoobarExamples)
    
    if(NOT TARGET X)
      find_package(Foobar CONFIG REQUIRED)
    endif()
    
    # Use X from Foobar
    target_link_library(my_exe X)
    

    【讨论】:

    • 我知道你来自哪里。这有两个问题:它使 CMakeLists.txt 变得不必要地混乱,我不能只使用X,因为我使用命名空间导出目标。然后代码会变得更加混乱。
    • ALIAS 目标旨在解决该问题(自 CMake 2.8.12 起)。 cmake.org/cmake/help/v3.0/manual/…
    • it makes the CMakeLists.txt unnecessarily messy 恕我直言,一个if 命令不乱
    • @steveire 我完全忘记了ALIAS 目标。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 2013-01-30
    相关资源
    最近更新 更多