cmakecmake-custom-command

How to parameterize cmake add_custom_command and add_custom_target?


I'm creating a library for micro-controller which as part of it's source will have couple of usage examples.

All CMakeList.txt files for the examples look very similar:

set(ESP_TARGET_FW1 "${CMAKE_CURRENT_BINARY_DIR}/${ESP_FW1}.bin")
set(ESP_TARGET_FW2 "${CMAKE_CURRENT_BINARY_DIR}/${ESP_FW2}.bin")

add_executable(esp_main main.c ${ESP_USER_CONFIG})
target_include_directories(esp_main PUBLIC include)
target_link_libraries(esp_main esp_sdo phy pp net80211)

# Create ESP8266 binary files.
add_custom_command(
    OUTPUT
        ${ESP_TARGET_FW1} ${ESP_TARGET_FW2}
    COMMAND
        ${ESPTOOL_PATH} elf2image $<TARGET_FILE:esp_main> -o ${CMAKE_CURRENT_BINARY_DIR}/
    DEPENDS
        esp_main
)

# Flash binary files to the device.
add_custom_target(esp_main_flash
    COMMAND
        ${ESPTOOL_PATH} -p ${ESP_PORT} -b ${ESP_BAUD} write_flash ${ESP_FW1} ${ESP_TARGET_FW1} ${ESP_FW2} ${ESP_TARGET_FW2}
    DEPENDS
        ${ESP_TARGET_FW1} ${ESP_TARGET_FW2}
)

Only the name of the example (esp_main) changes and where the generated binary files are created.

I'm looking to somehow parameterize add_custom_command and add_custom_target in case like this. Ideally include some file and have it define esp_main_flash target and custom command.


Solution

  • In CMake the most direct way for parameterize some sequence of actions (for later reuse) is creating a macro or a function. Both of them are allowed to perform any operation which can be written in a plain CMakeLists.txt.