[CMake] copy_if_different on build

Matthew Woehlke matthew.woehlke at kitware.com
Mon Apr 1 12:41:38 EDT 2013


On 2013-03-29 17:07, Skippy VonDrake wrote:
> I'll look closer at add_custom_command. I want the file to copy over if
> it has changed - at build time. Not cmake time. And not copy if it hasn't
> changed. But that may not be doable.
>
> Seems like every StackOverflow post I see has a different take on how
> to do this simple process.

That's a little surprising... as you say, this shouldn't be complicated. 
I believe what you want is:

  add_custom_command(
     OUTPUT "${output}"
     DEPENDS "${input}"
     COMMAND ${CMAKE_COMMAND} -E copy
             "${input}" "${output}"

...which is roughly equivalent to a Makefile rule like:

output: input
   cp input output

IOW, the file "${output}" depends on the file "${input}" (so the target 
will only run when "${input}" is newer than "${output}"), and will be 
created by copying "${input}" to "${output}" (using 'cmake -E' for 
portability).

Don't forget to have an actual target depend on "${output}" :-). 
(Probably you are using it as a source file for a library or executable, 
so there is no problem.)

You may also want to use 'copy_if_different' instead of just 'copy', 
which won't change the time stamp of "${output}" if the contents are the 
same as "${input}". On the plus side, this means that large targets 
depending on "${output}" won't be needlessly rebuilt/relinked. On the 
down side, the copy_if_different will remain out of date, and as a 
result still think it needs to run after a successful build.

-- 
Matthew



More information about the CMake mailing list