Post

08. find_package() Works in CMake

08. find_package() Works in CMake

How find_package() Works in CMake (Step-by-Step)


Prerequisites


1. Step-by-Step Guide

This post explains what actually happens when you call find_package() in CMake, including how .cmake files are located and executed.

2. Executable

2-1. Starting Point

1
find_package(OpenCV REQUIRED)

This single line triggers a multi-step process inside CMake.

2-2. Determine Search Mode

CMake tries two modes:

1) Config Mode (Preferred)

Search for:

1
2
OpenCVConfig.cmake
opencv-config.cmake

2) Module Mode (Fallback)

Search for:

1
FindOpenCV.cmake

Modern libraries (like OpenCV, fmt) use Config Mode

2-3. Search Paths

CMake searches in the following order:

  1. OpenCV_DIR (if manually set)
  2. CMAKE_PREFIX_PATH
  3. System install locations

Example:

1
set(OpenCV_DIR "C:/opencv/install/lib/cmake/opencv4")

2-4. Load the Config File

Once found:

1
include(OpenCVConfig.cmake)

This is the most important step. find_package() is essentially:

1
"find + include"

2-5. Config File Execution

The .cmake file is executed as code, not just read.

Inside OpenCVConfig.cmake:

1) Environment Detection

1
2
set(OpenCV_ARCH x64)
set(OpenCV_RUNTIME vc17)

Detect platform, compiler, architecture

2) Locate Actual Library Path

1
check_one_config(OpenCV_LIB_PATH)

Finds correct directory like:

1
x64/vc17/lib

3 Include Secondary Config

1
include("${OpenCV_LIB_PATH}/OpenCVConfig.cmake")

Delegates to the real config file

2-6. Define Variables

Inside the final config file:

1
2
3
set(OpenCV_INCLUDE_DIRS ...)
set(OpenCV_LIBS ...)
set(OpenCV_VERSION ...)

These become available in your project

2-7. Create Imported Targets

Modern CMake defines targets:

1
add_library(OpenCV::OpenCV IMPORTED)

And sets properties:

1
2
INTERFACE_INCLUDE_DIRECTORIES
IMPORTED_LOCATION

2-8. Dependency Propagation

1
target_link_libraries(OpenCV::OpenCV INTERFACE opencv_core opencv_imgproc)

👉 Dependencies are automatically passed to your target

2-9. Your Code Uses It

1
target_link_libraries(myapp OpenCV::OpenCV)
  • adds include directories
  • links libraries
  • propagates dependencies

3. Full Flow Summary

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
find_package(OpenCV)
        ↓
search OpenCVConfig.cmake
        ↓
include(OpenCVConfig.cmake)
        ↓
detect platform (x64, vc17, etc.)
        ↓
resolve actual library path
        ↓
include secondary config
        ↓
define variables + targets
        ↓
ready to use in your project
This post is licensed under CC BY 4.0 by the author.