Copy file example

Consider that we want a build step which copies and renames a file, and we only want it to be done when needed - i.e. if and only if:

This can be achieved using add_custom_command such that it adds a custom command to produce an output:


add_custom_command(
	OUTPUT out.txt 
	DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/in.txt
	COMMENT "copying file" 
	COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/in.txt out.txt)

Note that we cannot simply use a copy command on a custom target, because a custom target is always considered out of date.

cmake doesn't analyse the COMMAND parameter to work out the dependencies. Instead the dependencies have to be specified explicitly. In this case:

Note that out.txt is only generated if there is some downstream target that depends on it. For example, this could be achieved by declaring a custom target named T which is always built and depends on out.txt:


add_custom_target(T ALL DEPENDS out.txt)

This adds the following dependencies: