How to call a CMake function from add_custom_target/command?

I encountered this issue while writing a CMake build system for BVLC/Caffe. What I finally did is I put the function content into a separate CMake script and called it from within add_custom_target by invoking:

add_custom_target(target_name
    COMMAND ${CMAKE_COMMAND} -P path_to_script
)

Invoking CMake with -P flag makes it act as a scripting language. You can put any CMake functions inside the script.


I looked for the same and after a few minutes i realized that this is impossible because cmake is a build-generator generator.

This command will just be run at a different time, for example from within your IDE, when the cmake is just not existing.