find_program(_CLANG_FORMAT clang-format) if(_CLANG_FORMAT) add_executable(clang-format IMPORTED) set_target_properties(clang-format PROPERTIES IMPORTED_LOCATION ${_CLANG_FORMAT}) endif() unset(_CLANG_FORMAT) function(add_autoformat_target target) get_target_property(source_dir ${target} SOURCE_DIR) get_target_property(sources ${target} SOURCES) add_custom_target(autoformat_${target} COMMAND clang-format -i -- ${sources} WORKING_DIRECTORY ${source_dir} COMMENT "Autoformating sources of target ${target}" VERBATIM) if(NOT TARGET autoformat) add_custom_target(autoformat) endif() add_dependencies(autoformat autoformat_${target}) endfunction()