简体   繁体   中英

Do I always need a target in CMake?

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.

Everything executed during the building of a project is executed as a part of some target .

This is a concept of CMake and it correlates with the concepts of many build tools: Make, Ninja, MSVC, etc. Because CMake actually delegate work for building a project to one of those build tools, similarity of concepts is very important.

So yes, when you want to declare some command to be executed during the build, you need to add this command to some target:

  • add_custom_target creates new target
  • add_custom_command(TARGET) attaches the COMMAND to the specified target
  • add_custom_command(OUTPUT) attaches the COMMAND to the target, which DEPENDS on files given in OUTPUT clause.

Note, that while CMake has notion of all target, which is executed by default (when no target is specified), it doesn't allow COMMANDS to be directly attached to that target.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM