如何获取 ExternalProject 定义的目标的输出路径?

How to get the output path of a target defined by ExternalProject?

我正在构建 Google 的 FlatBuffers 作为我自己项目的依赖项,我需要在构建时编译一个模式。我不想使用 BuildFlatBuffers.cmakeFindFlatBuffers.cmake,因为我使用的是特定版本,我不能依赖它在本地安装。

这是我的CMakeLists.txt的简化版本:

ExternalProject_Add (
  flatbuf
  URL "https://github.com/google/flatbuffers/archive/v1.8.0.tar.gz"
  CMAKE_ARGS -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}
)
add_custom_target (
  flatbuf_schema
  PREFIX ${FLATBUF_PREFIX}
  DEPENDS flatbuf
  COMMAND ${FLATBUF_PREFIX}/src/flatbuf-build/flatc --cpp ${FLATBUF_SCHEMA}
)

它对 Make 和 Ninja 工作正常,但在 Xcode 中失败,它在 Debug 目录中构建 flatc

我考虑了这些可能的解决方案:

我尝试了(2)和(3)但没有成功。至于 (1),我不确定这是个好主意。如何以可移植的方式构建模式?

您可以使用 ExternalProject_Get_Property,像这样...

注意:我想您甚至不需要安装 flatbuf,只需构建并使用它即可。

ExternalProject_Add (
  flatbuf_project
  URL "https://github.com/google/flatbuffers/archive/v1.8.0.tar.gz"
  CMAKE_ARGS -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}
  INSTALL_COMMAND ""
)

ExternalProject_Get_Property(flatbuf_project source_dir)
ExternalProject_Get_Property(flatbuf_project binary_dir)

# Export flatbuf executable to consume schema file during build
add_executable(flatbuf::flatbuf IMPORTED)
set_target_properties(flatbuf::flatbuf PROPERTIES IMPORTED_LOCATION
    "${binary_dir}/flatc")
add_dependencies(flatbuf::flatbuf flatbuf_project)

add_custom_target(flatbuf_schema
  PREFIX ${FLATBUF_PREFIX}
  COMMAND flatbuf::flatbuff --cpp ${FLATBUF_SCHEMA}
)

注2:

If COMMAND specifies an executable target name (created by the add_executable() command) it will automatically be replaced by the location of the executable created at build time. If set, the CROSSCOMPILING_EMULATOR executable target property will also be prepended to the command to allow the executable to run on the host. Additionally a target-level dependency will be added so that the executable target will be built before this custom target.

注3: 不幸的是,目标 ALIAS 无法在 IMPORTED 目标上工作...

显然 CMake 提供了一个变量来解决这个问题,即 CMAKE_CFG_INTDIR (docs)。 flatc 可执行文件的路径应该是

ExternalProject_Get_Property(flatbuf BINARY_DIR)
set (FLATC "${BINARY_DIR}/${CMAKE_CFG_INTDIR}/flatc")