Visual Studio /delayload with CMake

CMAKE_LINK_LIBRARY_USING_FEATURE is a nice addition to CMake. CMake doesn’t have a built-in special /delayload delayed load import feature for MSVC-like compilers. Nonetheless, /delayload can be accomplished in a compact way as in the following example:

add_library(my SHARED lib.c)
add_executable(main main.c)

target_link_libraries(main PRIVATE my)

if(MSVC)
  set_property(TARGET my PROPERTY WINDOWS_EXPORT_ALL_SYMBOLS true)
  target_link_libraries(main PRIVATE delayimp)
  target_link_options(main PRIVATE "/DELAYLOAD:$<TARGET_FILE_BASE_NAME:my>.dll")
endif()