1

I have a python script, which generates some files for me, and in my script, I have an argument --outputdir to specify the location of output files. I want to run this script to generate these files and install them later. I used

add_custom_command(
 COMMAND python3.6 ${CMAKE_CURRENT_SOURCE_DIR}/generateFiles.py
 ARGS --outputdir ${CMAKE_CURRENT_BINARY_DIR})

So output files are generated under ${CMAKE_CURRENT_BINARY_DIR}, and I can install them later.

but above code did not work, because I have to use a TARGET or OUTPUT from the error message. So if I use a dummy one:

add_custom_target(dummy ALL)
add_custom_command(
     TARGET dummy
     COMMAND python3.6 ${CMAKE_CURRENT_SOURCE_DIR}/generateFiles.py
     ARGS --outputdir ${CMAKE_CURRENT_BINARY_DIR})

This just worked and I can see files are generated under ${CMAKE_CURRENT_BINARY_DIR}. I believe if I use something like:

add_custom_target(dummy 
                  COMMAND python3.6 ${CMAKE_CURRENT_SOURCE_DIR}/generateFiles.py
                   ARGS --outputdir ${CMAKE_CURRENT_BINARY_DIR})

this should also work. My question is why do I need a dummy target anyway? Actually just with COMMAND I can run my script and with args I can specify where the output files are generated, then with some install command I can install files around. So Am I correct to use a dummy target in this case and do I have to use a it? Note generateFiles.py are not changed during the build process and will generate the same files every time. Thanks, i am new to CMake.

4

1 回答 1

1

在项目构建期间执行的所有操作都是作为某个目标的一部分执行的。

这是 CMake 的一个概念,它与许多构建工具的概念相关:Make、Ninja、MSVC 等。因为 CMake 实际上将构建项目的工作委托给其中一个构建工具,所以概念的相似性非常重要。

所以是的,当你想在构建过程中声明一些要执行的命令时,你需要将此命令添加到某个目标:

  • add_custom_target创建新目标
  • add_custom_command(TARGET)将命令附加到指定的目标
  • add_custom_command(OUTPUT)将命令附加到目标,这取决于 OUTPUT 子句中给出的文件。

请注意,虽然 CMake 具有all默认执行的目标概念(当未指定目标时),但它不允许 COMMANDS 直接附加到该目标。

于 2022-01-14T18:42:05.920 回答