0

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?

einpoklum
  • 118,144
  • 57
  • 340
  • 684

1 Answers1

1

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()
einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • You could use `get_filename_component(target_filename "${target_basename}.fatbin" BASE_DIR ${CMAKE_CURRENT_BIRARY_DIR})`, if you want to ensure an absolute path and similar for the source file. But if you want to allow both absolute and relative paths to be specified, you should also extract the file name to determine the name of the custom target: `get_filename_component(custom_target_prefix ${target_basename} NAME)`... If you want to allow reuse of the functionality accross several subdirectories, you may need to find a way of generating unique names for the custom targets btw... – fabian Jan 01 '22 at 22:06
  • @fabian: Ok, but - is this the basic approach people use? Is there some other way to do it? – einpoklum Jan 01 '22 at 22:08
  • I'm not aware of any other possibility of generating a make rule(or equivalent), unless there's some specific functionality provided by a cmake module that provides similar functionality or builtin functionality like qt mocking functionality. Also I'm not familiar with cuda so I cannot make any statements on whether the dependencies could be expressed in a better way, like adding those to a existing executable target or something like this... – fabian Jan 01 '22 at 22:12
  • @fabian: Anyway... I want to allow the same kind of invocation as with `add_executable()`. Could I trouble you to edit the answer to make your suggestion more concrete? – einpoklum Jan 01 '22 at 22:17