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.