Cmake Find_package [work] Download May 2026

: Automatically calls find_package(googletest) before attempting a download.

Effective dependency management in C++ often requires a balance between using pre-installed system libraries and downloading external source code on the fly. While the find_package command is designed to locate already installed packages, modern CMake (version 3.24+) allows you to seamlessly integrate it with the FetchContent module to automatically download dependencies if they aren't found on the system. Understanding the Difference

: Searches for pre-installed libraries in standard system paths or user-defined directories like CMAKE_PREFIX_PATH . It is fast because it uses already compiled binaries. cmake find_package download

# Attempt to find the package quietly first find_package(libssh QUIET) if(NOT libssh_FOUND) message(STATUS "libssh not found, downloading from source...") include(FetchContent) FetchContent_Declare( libssh GIT_REPOSITORY https://git.libssh.org/projects/libssh.git GIT_TAG master ) FetchContent_MakeAvailable(libssh) else() message(STATUS "libssh found on system.") endif() # Link against the target (works whether found or fetched) target_link_libraries(my_app PRIVATE ssh) Use code with caution. Best Practices for "Find or Download" Make FetchContent compatible with find_package

The most idiomatic way to handle "find or download" is using the FIND_PACKAGE_ARGS and OVERRIDE_FIND_PACKAGE options within FetchContent . This allows your project to stay flexible: it will use a system-installed version if available, but fall back to downloading the source if necessary. Best Practices for "Find or Download" Make FetchContent

: Downloads source code (from Git, ZIPs, etc.) during the configuration step and adds it directly to your build tree. This ensures reproducibility but increases build times as dependencies are compiled from source. Method 1: The Modern Way (CMake 3.24+)

include(FetchContent) # 1. Declare the dependency with fallback download info FetchContent_Declare( googletest GIT_REPOSITORY https://github.com GIT_TAG v1.14.0 FIND_PACKAGE_ARGS # Tells FetchContent to try find_package() first ) # 2. Make it available (will either find it or download/add_subdirectory) FetchContent_MakeAvailable(googletest) # 3. Use the target as normal target_link_libraries(my_project PRIVATE GTest::gtest_main) Use code with caution. cmake find_package download

: If you specify this in FetchContent_Declare , any subsequent calls to find_package() in your subprojects will be redirected to the version managed by FetchContent. Method 2: The Manual Fallback (Legacy Support) If you are using an older version of CMake or