Table of Contents

CMake Finding Dependencies

find_package(PackageName) searches for an installed package and creates targets to link against. CMake searches standard paths, CMAKE_PREFIX_PATH, and system paths for package metadata (typically .cmake files).

Basic usage:

find_package(Eigen3 REQUIRED)
 
add_executable(myapp main.cpp)
target_link_libraries(myapp PRIVATE Eigen3::Eigen3)

This finds Eigen3 and creates the target Eigen3::Eigen3. If REQUIRED is specified, CMake fails if the package isn't found. Without it, the search is optional:

find_package(Boost)
if(Boost_FOUND)
  target_link_libraries(myapp PRIVATE Boost::system)
else()
  message(STATUS "Boost not found, some features disabled")
endif()

The package sets variables like <PackageName>_FOUND, <PackageName>_VERSION, <PackageName>_INCLUDE_DIRS. Modern packages prefer target-based exports (cleaner, handles dependencies automatically).

Finding by version:

find_package(OpenGL 4.6 REQUIRED)

Specifying search paths:

find_package(MyLib HINTS /opt/mylib/lib/cmake)
find_package(MyLib PATHS /home/user/lib/cmake)

HINTS are checked first; PATHS are fallbacks.

Module vs. config mode:

find_package(OpenGL)              # module mode: finds FindOpenGL.cmake
find_package(MyLib CONFIG)        # config mode: finds MyLibConfig.cmake
find_package(MyLib MODULE)        # module mode: finds FindMyLib.cmake

CMake looks in:

For packages not installed system-wide, set CMAKE_PREFIX_PATH:

cmake -DCMAKE_PREFIX_PATH=/opt/mylibs ..

Or add to CMakeLists.txt:

list(APPEND CMAKE_PREFIX_PATH "/opt/mylibs")
find_package(MyLib REQUIRED)

Use find_package() for all external dependencies (libraries, frameworks). Always use target-based linking (e.g., PackageName::LibName) rather than raw variables for portability.