add_custom_command has a form which can be used to add a custom command to a target such as a library or executable which runs either just before or just after the target is built.
For example, the following post build event copies the executable to some folder:
add_executable(myprog main.c)
add_custom_command(
TARGET myprog
POST_BUILD
COMMAND ${CMAKE_COMMAND} -E make_directory ${PROJECT_BINARY_DIR}
COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:myprog> ${PROJECT_BINARY_DIR}/.)
When the command will happen is determined by which of the following is specified:
There is a restriction which is imposed: The target in the TARGET signature of add_custom_command() must exist and must be defined in the current directory. This usually means you will add the build event command in the same file that adds the target to which it refers.