CodeBlanks Logo Icon CodeBlanks

find_package

Learn to find libraries with find_package.

What is find_package?

The find_package command locates an installed library on the system and makes it ready to use. The found library is exposed as imported targets. You link these targets to your own with target_link_libraries.

Example: find_package(Threads REQUIRED) finds the system threading library. Then target_link_libraries(myapp PRIVATE Threads::Threads) links it. The REQUIRED keyword makes the build fail if the library is not found. Header and link paths are automatically defined inside the imported target.

Common find_package usages

In real projects the most common libraries are: find_package(Boost), find_package(OpenCV), find_package(Qt6). Each exposes its own imported targets: Boost::system, Qt6::Core and so on.

Example: find_package(Boost REQUIRED COMPONENTS system) searches for Boost.system. You link it with target_link_libraries(myapp PRIVATE Boost::system). The COMPONENTS keyword searches only the requested sub-libraries. The found targets also carry header paths; so no extra include_directories call is needed.

Practice Link with find_package

Write a CMakeLists.txt. Add cmake_minimum_required(VERSION 3.20) and project(MyApp). Find the threading library with find_package(Threads REQUIRED). Define add_executable(myapp main.cpp). Link it with target_link_libraries(myapp PRIVATE Threads::Threads).

Starter code

main.cpp
# CMakeLists.txt
# Add cmake_minimum_required, project, find_package and link

Sample solution

main.cpp
cmake_minimum_required(VERSION 3.20)
project(MyApp)
find_package(Threads REQUIRED)
add_executable(myapp main.cpp)
target_link_libraries(myapp PRIVATE Threads::Threads)

Expected output

Dependency ready

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does find_package do?

  • Locates an installed library on the system Correct answer
  • Creates a new library
  • Configures the compiler
  • Generates source files

Explanation: find_package searches for a system library and prepares it for use.

2 Match each piece to its role

Term Meaning
find_package(Threads) Finds the library
REQUIRED Errors if not found
Threads::Threads Imported target
target_link_libraries Links to a target

3 Complete the find_package command

Question
____(Threads REQUIRED)
Answer
find_package(Threads REQUIRED)

Explanation: find_package(Threads REQUIRED) finds the threading library.

All lessons in Advanced