5

我有一个 CMake 项目Foobar,其中包含一个子目录,该子目录examples也可以用作独立的 CMake 构建。为此,此子目录执行 afind_package(Foobar)并使用导出的目标。Foobar提供 a FoobarConfig.cmakeFoobarConfigVersion.cmake和 aFoobarExports.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

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

4

1 回答 1

4

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

### 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)
于 2014-07-10T12:45:43.867 回答