0

I have a lot of custom CMake commands, so I end up with a lot of repetition of this pattern in build scripts, e.g.

set(PREREQ ${CMAKE_CURRENT_SOURCE_DIR}/foo.txt ${CMAKE_CURRENT_SOURCE_DIR}/bar.txt)
add_custom_command(
    OUTPUT baz.txt
    COMMAND cat ${PREREQ} > baz.txt
    DEPENDS ${PREREQ}
)
add_custom_target(a ALL DEPENDS baz.txt)

Are there equivalents of GNU Make automatic variables in CMake ($@, $<, etc) so I can avoid specifying inputs/outputs twice (dependencies, output, and command)?

How else can I DRY it up?

Alex B
  • 82,554
  • 44
  • 203
  • 280

1 Answers1

1

How about using custom functions? For your example script this could look like this:

function (add_custom_command_with_target _targetName _output)
    add_custom_command(
        OUTPUT ${_output}
        COMMAND cat ${ARGN} > ${_output}
        DEPENDS ${ARGN}
    )
    add_custom_target(${_targetName} ALL DEPENDS ${_output})
endfunction()

The function can be invoked in the following way:

add_custom_command_with_target(a baz.txt ${CMAKE_CURRENT_SOURCE_DIR}/foo.txt ${CMAKE_CURRENT_SOURCE_DIR}/bar.txt)

In the function body you can use the predefined variable ARGN, which holds the list of arguments past the last expected argument. This is the closest thing you can get to GNU Make's predefined variables.

sakra
  • 62,199
  • 16
  • 168
  • 151