My first guess was like this:
function(add_clean_target target)
set(clean_target clean.${target})
add_custom_command(
OUTPUT ${target}.cleaned
COMMAND cmake -E rm -f $<TARGET_FILE:${target}>
COMMAND cmake -E rm -f $<TARGET_OBJECTS:${target}>
DEPENDS_EXPLICIT_ONLY
COMMAND_EXPAND_LISTS
)
add_custom_target(${clean_target} DEPENDS ${target}.cleaned)
set_property(TARGET ${clean_target} PROPERTY FOLDER "Utilities")
endfunction()
add_clean_target(my_lib)
But turns out that the name add_clean_target
for this function would better sound like clean_or_built_target
because in most of my conditions it cleans the target after build, and the next time this target is invoked, it builds the target back. Anyway it does the work when needed, and all dependent targets are rebuilt after when necessary. But I landed with other solution (MSW specific a.t.m.):
function(add_clean_target target)
set(clean_target clean.${target})
set(cleanup_script ${target}.clean.bat)
set(target_output "$<SHELL_PATH:$<TARGET_FILE:${target}>>")
set(target_objects "$<JOIN:$<SHELL_PATH:$<TARGET_OBJECTS:${target}>>,\" \">")
set(delete "del /Q /S")
set(command "${delete} \"${target_output}\" \"${target_objects}\"")
add_custom_command(
TARGET ${target}
POST_BUILD
COMMENT "Writing `${target}` cleanup script"
COMMAND cmd /c > ${cleanup_script} echo ${command}
DEPENDS_EXPLICIT_ONLY
COMMAND_EXPAND_LISTS
)
set(error "Cleanup script ${cleanup_script} not found. Try to [re]build `${target}` target")
set(command "echo off & if exist ${cleanup_script} (call ${cleanup_script}) else (echo ${error})")
add_custom_target(${clean_target}
COMMENT "Cleaning target `${target}`"
COMMAND cmd /c ${command}
)
set_property(TARGET ${clean_target} PROPERTY FOLDER "Utilities")
endfunction()
Comments and improvements are welcomed also! Would be nice to get it right and crossplatform