Conditional (target/dependency based) fetchcontent?

In the following pseduo-scenario, I’d like fetch content to only fetch/do anything when the dependent target is being built.

Include(FetchContent)
Add_Library(
  MyLib
  ...
)

FetchContent_Declare(
  fmt
  ...
)
FetchContent_MakeAvailable(fmt)

Add_Executable(
  LibValidation
  EXCLUDE_FROM_ALL
  ...
)
Target_Link_Libraries(
  LibValidation
  fmt::fmt
)

How can I set something like this up with CMake 3.19?

-Oliver

FetchContent works at CMake configure time. It will do the download during CMake configure, but things it adds to the build still only build at build time like everything else. If you want to have the download performed at build time too and only if something requires it, then you want ExternalProject rather than FetchContent. Note that switching to ExternalProject means you won’t have access to anything from your dependency (fmt in this case) during CMake’s configure step, so you won’t have things like the fmt::fmt library defined for you.

1 Like