# 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: ```cmake 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: ```cmake 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 `_FOUND`, `_VERSION`, `_INCLUDE_DIRS`. Modern packages prefer target-based exports (cleaner, handles dependencies automatically). Finding by version: ```cmake find_package(OpenGL 4.6 REQUIRED) ``` Specifying search paths: ```cmake 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: ```cmake 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: - `/usr/share/cmake-X.Y/Modules/` (built-in modules) - `${CMAKE_PREFIX_PATH}/lib/cmake/` (installed packages) - `/usr/local/lib/cmake/` - `/usr/lib/cmake/` For packages not installed system-wide, set `CMAKE_PREFIX_PATH`: ```bash cmake -DCMAKE_PREFIX_PATH=/opt/mylibs .. ``` Or add to CMakeLists.txt: ```cmake 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.