c++ - CMake:在构建项目时执行 C++ 文件

标签 c++ cmake

我正在开发一个 C++ 项目,我想在构建时执行一个脚本来生成一些文件。我对 CMake 不是很熟悉,所以我需要一些帮助。

我所说的脚本是指项目中的 .cpp 文件。

我已经设法获得了以下内容:

   set(PrecisionCommand
      ${CMAKE_SOURCE_DIR}/src/main/matlab/matlabprecision.cpp
   )
   set(precision_output_files
      ${CMAKE_SOURCE_DIR}/work/variables.txt
   )

   add_custom_command(
      OUTPUT ${precision_output_files}
      COMMAND ${PrecisionCommand}
      COMMENT "Running ${PrecisionCommand}"
   )


   add_custom_target(allocate_generate DEPENDS ${precision_output_files})

现在发生的是 matlabprecision.cpp 文件在文本编辑器中打开,而不是被执行。我该如何解决这个问题?

最佳答案

因为.c文件不是脚本而是源文件,不能直接执行。但是,您可以先将其编译成可执行文件:

add_executable(PrecisionCommand ${CMAKE_SOURCE_DIR}/src/main/matlab/matlabprecision.cpp)

然后运行该可执行文件:

add_custom_command(
  OUTPUT ${precision_output_files}
  COMMAND PrecisionCommand
  COMMENT "Running PrecisionCommand"

)

请注意,COMMAND 选项使用目标名称 来运行可执行文件。 CMake 了解该用法并:

  • 将目标名称转换为可执行文件的路径
  • 在创建可执行文件和运行它之间添加适当的依赖关系

来自关于 add_custom_command 的文档:

If COMMAND specifies an executable target (created by ADD_EXECUTABLE) it will automatically be replaced by the location of the executable created at build time. Additionally a target-level dependency will be added so that the executable target will be built before any target using this custom command.

关于c++ - CMake:在构建项目时执行 C++ 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41378245/

相关文章:

c++ - 如何在 Linux 中编译 Box2D?

c++ - 如何使用 CMake 在 android 构建上编译和共享两个 c++ 库

regex - 如何为 CTest 指定正则表达式

c++ - 控制QTimer的时间?

c++ - 下面的 C++ 代码有什么问题?

c++ - 错误 C2440 和仿函数

c++ - glfw3 编译 undefined reference

c++ - 如何在编译时门功能?

c++ - 交叉编译中的 CMake CMAKE_AUTOMOC

c++ - 德州仪器数字信号处理器 : interfacing C++ and assembly