Post copy files to currently building target directory.

Hi, I have a cmake project that contains multiple libs and multiple exes (mostly tests and demos).

Is there any way to setup cmake to copy data files from one of the libs to whichever exe target is being built?

I have tried this:

add_custom_command(
        TARGET scene POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E copy_directory
                ${CMAKE_CURRENT_SOURCE_DIR}/shaders
                ${CMAKE_CURRENT_BINARY_DIR}/shaders)

But the dir is always copied to the same place, I assume because the the output dir is ‘fixed’ at cmake config time (?) whereas I want the output dir to change depending on what target I’m building.

For example, if I’m building demo1 I want the output dir to be demo1s binary dir, if I’m building demo2, demo2’s binary dir etc.

Is this possible? Or is every CMAKE_* path fixed after config time? Alternatively, is there a way to may be copy data files in from a different target?

Your custom command is already attached to a specific target (scene in this case). I’ll assume you are looking for a way to generalise this so that you can call a function that adds an equivalent custom command to a target passed in as a function argument. You can use generator expressions to specify a target-specific location. Here’s how you might implement the equivalent to the example in your original post:

function(copy_shaders_to_target_dir target)
    add_custom_command(
        TARGET ${target} POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E copy_directory
            "$<TARGET_PROPERTY:${target},SOURCE_DIR>/shaders"
            "$<TARGET_PROPERTY:${target},BINARY_DIR>/shaders"
    )
end function()

The above function could only be called in the same directory scope as the one in which the target was defined (i.e. where add_library() or add_executable() was called).

You might also want to look at generator expressions like $<TARGET_FILE_DIR:...>, which might be a better fit for what you seem to be wanting to do (especially if you want to support multi-config generators like Visual Studio, Xcode or Ninja Multi-Config).

1 Like

That’s very useful thanks, I didn’t know about TARGET_PROPERTY…

It’s still a little intrusive on the target side, but a big improvment over copying and pasting code around!

I haven’t looked into ‘generators’ yet (they seem a little scary for some reason) but I will do now…