Idiomatic way to handle packages and add_subdirectory?

Currently I work on a project where users want both add_subdirectory and find_package. We try and support both approaches.

However, it results in having code that looks like this.

if (NOT TARGET Vulkan::Headers)
    find_package(VulkanHeaders CONFIG REQUIRED QUIET)

Is there a better way?

I think it’s better to be more proactive about these kinds of things. Have a variable about whether to use external copies or not and do that. These fallbacks only make weird states when things go as one isn’t expecting and it looks like it’s working when it’s really getting the wrong thing.

option(use_external_vulkan "blah" ${use_external_default})
if (use_external_vulkan)
  find_package(VulkanHeaders CONFIG)
  if (NOT VulkanHeaders_FOUND)
      "External Vulkan requested, but not found: ${VulkanHeaders_NOT_FOUND_MESSAGE}")
  endif ()
else ()
endif ()
# TODO: set up an INTERFACE target to patch over differences
1 Like