How can I generalize a custom command into a generic-make-rule-like construct?

126 views Asked by At

In this question:

How can I build a fatbin file using CMake?

we saw how to formulate a pair of add_custom_command() and add_custom_target() commands, for building a .fatbin file out of a .cu file:

add_custom_command(
    OUTPUT my_src.fatbin
    COMMAND ${CMAKE_CUDA_COMPILER} -fatbin -o foo.fatbin 
        "${CMAKE_CURRENT_SOURCE_DIR}/my_src.cu"
    MAIN_DEPENDENCY my_src.cu
)
add_custom_target(dummy ALL DEPENDS my_src.fatbin)

. The details of what these files are and how they are used is immaterial to this question (I hope); what I would like to do is generalize these two specific commands so that I don't just build my_src.fatbin from my_src.cu, but so that I can easily build any .cu file I specify into a .fatbin file. Essentially, the equivalent of Make's:

$(OBJDIR)/%.fatbin : $(SRCDIR)/%.cu
        $(CUDA_COMPILER) $(CUDA_CPP_FLAGS) -fatbin -o $@ $<

What's the appropriate idiom for doing that?

1

There are 1 answers

4
einpoklum On

Perhaps a function is the right approach. Something like this? :

function(add_fatbin target_basename source_file)
    # TODO: Should I check target_basename isn't a full path?
    set(target_filename "${target_basename}.fatbin")
    add_custom_command(
        OUTPUT "${target_filename}"
        COMMAND ${CMAKE_CUDA_COMPILER} -fatbin -o "${target_filename}"
            "${source_file}"
        MAIN_DEPENDENCY "${source_file}"
    )
    add_custom_target("${target_basename}_fatbin_tgt" ALL DEPENDS "${target_filename}")
endfunction()