CMake:就地创建对象和可执行文件

CMake: creating object and executable inplace

我有以下设置:

data/
  Makefile
src/
  main.cpp
CMakeLists.txt

data/Makefile 通过 all 目标创建文件 data/file

src/main.cpp需要读作data/file,例如

// src/main.cpp
...
      auto is = std::ifstream{"data/file"};
...

如何指定 src/main.cpp 的可执行目标应取决于 data/Makefile 的输出?

add_custom_targetCMake documentation 状态

Adds a target with the given name that executes the given commands. The target has no output file and is always considered out of date even if the commands try to create a file with the name of the target. Use the add_custom_command() command to generate a file with dependencies. By default nothing depends on the custom target. Use the add_dependencies() command to add dependencies to or from other targets.

使用该提示,我发现了以下工作方式:

top-level CMakeLists.txt

# CMakeLists.txt
add_subdirectory(data)
add_executable(my_exec src/main.cpp)
add_dependencies(my_exec data_files)

data/中的CMakeLists.txt

# data/CMakeLists.txt
add_custom_command(OUTPUT ${CMAKE_CURRENT_SOURCE_DIR}/file
                   COMMAND make all
                   DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/Makefile 
                   WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
                   )
add_custom_target(data_files
                  DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/file)