CMake:将文件从构建目录复制到源目录

CMake: Copy files from build directory to source directoy

我的 C++ 程序读写文件。要将输入文件从源目录 复制到需要它们的构建目录 ,我在 CMakeLists.txt:

中使用了这一行
configure_file(<input> <output> COPYONLY)

作为积极的副作用,QtCreator 在其项目视图中列出了文件。

有没有办法自动将文件从构建目录复制到源目录,这样我就可以在源目录中获得更新的输出文件,并在 QtCreator 的项目视图中列出?

如果您对此感到满意,您可以使用带有绝对路径的相同命令:

configure_file(${CMAKE_BINARY_DIR}/<path>/<input> ${CMAKE_SOURCE_DIR}/<path>/<output> COPYONLY)

其中 CMAKE_BINARY_DIR 是:

[...] the full path to the top level of the current CMake build tree.

CMAKE_SOURCE_DIR 是:

[...] the full path to the top level of the current CMake source tree.

根据documentationconfigure_file仅当<input><output>是相对路径时才以自定义方式处理,否则直接使用它们。
换句话说:

  • <input> 是一个文件名,其中:

    A relative path is treated with respect to the value of CMAKE_CURRENT_SOURCE_DIR.

    绝对路径只是按原样使用。

  • <output> 是文件名或目录:

    A relative path is treated with respect to the value of CMAKE_CURRENT_BINARY_DIR.

    绝对路径只是按原样使用。


您可以使用的另一种可能方法是依赖 file 命令及其(假设)COPY 版本。来自文档:

The COPY signature copies files, directories, and symlinks to a destination folder. Relative input paths are evaluated with respect to the current source directory, and a relative destination is evaluated with respect to the current build directory. Copying preserves input file timestamps, and optimizes out a file if it exists at the destination with the same timestamp. Copying preserves input permissions unless explicit permissions or NO_SOURCE_PERMISSIONS are given (default is USE_SOURCE_PERMISSIONS).

显然可以像 configure_file 一样直接使用绝对路径,并且它们保持不变。相对路径的处理方式与通常 cmake.

不同