25

Is it possible to call a CMake function out of an add_custom_target or add_custom_command?

I know I could move the CMake function to a Python (or whatever) script and call it from add_custom_target/command but I would like to avoid having tons of script next to the existing CMake infra.

What I want to achieve is to use CPack for generating a zip package of binary artifacts and publish them in an artifact repository. For the publishing part I have already the CMake function created but now I need to combine the packaging and publishing together.

Thanks for any help/hints in advance.

Tsyvarev
  • 60,011
  • 17
  • 110
  • 153
Martin
  • 968
  • 3
  • 10
  • 19
  • 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. – Lothar Dec 18 '18 at 15:04

1 Answers1

38

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.

Adam Kosiorek
  • 1,438
  • 1
  • 13
  • 17
  • 25
    It boggles my mind that you cannot call cmake commands like FILE directly from within add_custom_command – xaxxon Apr 21 '16 at 09:38
  • Looks interesting, are parent CMake file definitions retained? – Rastikan Jan 12 '17 at 16:16
  • 6
    Actually, I found out that it doesn't BUT you can add a bunch of -D switched to 'forward' existing definitions to the child CMake script: add_custom_command( OUTPUT Dockerfile.base COMMAND ${CMAKE_COMMAND} -D DISTRO_NAME=${DISTRO_NAME} -D DISTRO_VERSION=${DISTRO_VERSION} -D PROJECT_TEMPLATE_DIR=${PROJECT_TEMPLATE_DIR} -P ${CMAKE_MODULE_PATH}/ConfigureDockerfileBase.cmake COMMENT "Configure the Dockerfile.base file." ) – Rastikan Jan 12 '17 at 16:40
  • 1
    What if I want to implement such logic: execute that script only when a variable is defined ? How should I write this in `add_custom_target` ? @Adam – Lewis Chan Sep 29 '18 at 12:14
  • Works great when the function is in a `.cmake` file, is there an option to call a function defined on the same CMakeLists.txt file ? @Adam Kosiorek – joepol Sep 22 '20 at 12:12
  • How to return values from that script ? – Ragul Mar 30 '21 at 13:36
  • @Ragul [How to set the global variable in a function for cmake?](https://stackoverflow.com/q/10031953/12447766) – Burak May 26 '23 at 06:50