0

I have a CMake project with next post_build command:

add_custom_command(TARGET ncd_json
                   POST_BUILD
                   COMMAND ${CMAKE_COMMAND} -E copy
                   ${CMAKE_CURRENT_SOURCE_DIR}/ncd.json
                   $<TARGET_FILE_DIR:ncd_json>/ncd.json
                   COMMENT "Copy ncd.json into binaries folder"
                   )

ncd.json is copied every time target build. But I really need to copy this file only if it is changed, and even if target is already built and this is the main problem.

I think this question is not full duplicate of CMake copy if original file changed but supplements it.

Community
  • 1
  • 1
kyb
  • 7,233
  • 5
  • 52
  • 105

2 Answers2

4

Something like the following should do close to what you want:

add_custom_target(copyJson ALL
    COMMAND ${CMAKE_COMMAND} -E copy_if_different
            ${CMAKE_CURRENT_SOURCE_DIR}/ncd.json
            $<TARGET_FILE_DIR:ncd_json>/ncd.json
)
add_dependencies(copyJson ncd_json)

It will only copy the file if it is different and it will still copy if the target is already built. Note, however, that it won't copy if you ask only for the target itself to be built. The above relies on you building the default target to get the file copied. You could always combine the approach in your question with the above and it would probably be robust for the cases you want.

Craig Scott
  • 9,238
  • 5
  • 56
  • 85
0

While writing question I found a good answer here

configure_file(input_file output_file COPYONLY)

or in my case

configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/ncd.json 
            ${CMAKE_CURRENT_BINARY_DIR}/ncd.json
            COPYONLY
            )

But I still not sure if it copies ncd.json every time or not...

See also documentation.

Community
  • 1
  • 1
kyb
  • 7,233
  • 5
  • 52
  • 105
  • 1
    `configure_file()` will copy the file every time. Note, however, that your code here is not necessarily copying to the same location as your question. Specifically, if you are using the Visual Studio or Xcode generators, they use configuration-specific build directories. – Craig Scott May 19 '17 at 09:42
  • 1
    @CraigScott: "`configure_file()` will copy the file every time." - Actually, it will not. New [documentation](https://cmake.org/cmake/help/latest/command/configure_file.html) clearly states that resulted file is modified only when its **content** is needed to be **changed**. – Tsyvarev Oct 26 '21 at 20:02
  • Indeed, I don't know why I made that claim at the time. Thanks for pointing that out. – Craig Scott Oct 26 '21 at 20:50