skip to content

In CMake, why link the imported target ZLIB::ZLIB after find_package(ZLIB) instead of using ZLIB_INCLUDE_DIRS and ZLIB_LIBRARIES?

level: juniorimportance: must knowfreq 60%

answer

  1. a target carries its own requirements
  2. names with :: are checked
  3. per-configuration library locations
  4. PkgConfig:: from IMPORTED_TARGET

basics

~20 s

An imported target bundles the include directories, link file and other usage requirements in one name, so a single target_link_libraries call applies them all, CMake errors on a misspelled name, and per-configuration library paths are chosen for you.

solid answer

~40 s

`find_package(ZLIB)` runs CMake's `FindZLIB` module, which sets result variables and also creates the **imported target** `ZLIB::ZLIB`. An imported target describes a library that exists outside the build: `IMPORTED_LOCATION` (or `IMPORTED_LOCATION_RELEASE` and `_DEBUG`) holds the file, and `INTERFACE_*` properties hold what a consumer needs. `target_link_libraries(app PRIVATE ZLIB::ZLIB)` therefore adds the include path and the library together and lets them propagate like any other target's usage requirements. The variables do none of that: you must copy each one into the right command, nothing propagates, and a typo expands to an empty string silently. A name containing `::` must be an imported or alias target, so a misspelling stops configure with an error. The same applies to `pkg_check_modules(... IMPORTED_TARGET ...)`, which creates `PkgConfig::<prefix>`.

code

cmake · 9 lines
cmake
cmake_minimum_required(VERSION 3.25)
project(compressor CXX)

find_package(ZLIB REQUIRED)
message(STATUS "zlib ${ZLIB_VERSION}")

add_executable(compressor main.cpp)
# One name brings the include path, the library file and any extra requirements
target_link_libraries(compressor PRIVATE ZLIB::ZLIB)

go deeper

for a junior

Know that find_package gives you a namespaced target such as ZLIB::ZLIB and that one target_link_libraries line with it replaces separate include and library wiring.

for a middle

Explain what an imported target is: IMPORTED_LOCATION per configuration plus INTERFACE properties, no build rules, and the :: name check that turns a typo into a configure error.

for a senior

Recognize the directory-scope trap when find_package sits in a subdirectory, and wrap variable-only dependencies in your own INTERFACE IMPORTED target so the project links one name.

for a principal

Set the rule that every dependency is consumed through a target, so swapping a system package for a fetched or package-manager build changes one discovery line and no consumer.

## What find_package hands back When `find_package(ZLIB REQUIRED)` succeeds, CMake has loaded a script that describes zlib. For zlib that script is the `FindZLIB` module shipped with CMake, and it reports the result in two forms: - **result variables** such as `ZLIB_FOUND`, `ZLIB_VERSION`, `ZLIB_INCLUDE_DIRS` and `ZLIB_LIBRARIES`; - an **imported target**, `ZLIB::ZLIB`, which `FindZLIB` creates only when zlib was found. An **imported target** is a target that CMake does not build. It is created with `add_library(<name> <type> IMPORTED)` and points at files that already exist: `IMPORTED_LOCATION` names the library file, and per-configuration variants such as `IMPORTED_LOCATION_RELEASE` and `IMPORTED_LOCATION_DEBUG` let one target hold several builds. Its **usage requirements** live in the same `INTERFACE_*` properties a library built in the project uses: `INTERFACE_INCLUDE_DIRECTORIES`, `INTERFACE_COMPILE_DEFINITIONS`, `INTERFACE_LINK_LIBRARIES` and so on. ## Variables versus a target | Concern | `ZLIB_INCLUDE_DIRS` and `ZLIB_LIBRARIES` | `ZLIB::ZLIB` | |---|---|---| | How many commands to wire it | one per variable | one `target_link_libraries` | | Propagates to consumers of your library | no, you repeat it | yes, through `PUBLIC` or `INTERFACE` | | Debug and release library files | packed in one list with keywords | chosen per configuration | | A typo in the name | expands to empty, builds may fail much later | configure stops with an error | | Extra flags the library needs | only if you remember them | carried in the target's properties | With variables, a project has to repeat the wiring in every target that uses zlib: ```cmake # Older style: every consumer must repeat both lines target_include_directories(app PRIVATE ${ZLIB_INCLUDE_DIRS}) target_link_libraries(app PRIVATE ${ZLIB_LIBRARIES}) ``` With the imported target, one line does it and the requirements travel with the name: ```cmake find_package(ZLIB REQUIRED) add_executable(app main.cpp) target_link_libraries(app PRIVATE ZLIB::ZLIB) ``` ## Why the double colon matters The `::` in `ZLIB::ZLIB` is a naming convention for namespaced imported and alias targets, and CMake enforces it. Since policy `CMP0028` (whose old behaviour CMake 4.0 removed), a link item that contains `::` but is not an imported or alias target is a fatal configure error. Misspelling the name as `ZLIB::zlib` produces: ```plaintext CMake Error at CMakeLists.txt:5 (target_link_libraries): Target "app" links to: ZLIB::zlib but the target was not found. Possible reasons include: * There is a typo in the target name. * A find_package call is missing for an IMPORTED target. ``` A misspelled variable, by contrast, simply expands to nothing, and the failure surfaces later as a missing header or an undefined symbol. ## Where the target is visible An imported target is by default visible only in the directory that created it and its subdirectories. A `find_package` call in `src/net/CMakeLists.txt` creates a `ZLIB::ZLIB` that a sibling directory cannot see. Two ways to widen that: 1. call `find_package` in the top-level `CMakeLists.txt`, before the `add_subdirectory` calls; 2. pass `GLOBAL` to `find_package`, or set `CMAKE_FIND_PACKAGE_TARGETS_GLOBAL` (both since CMake 3.24), to promote the imported targets to global scope. ## Config packages define the same kind of target A library that installs its own config package, such as an internal `Ledger` library from another repository, usually defines namespaced imported targets in that file. `find_package(Ledger CONFIG REQUIRED)` then gives you `Ledger::ledger`, and the target's `INTERFACE_LINK_LIBRARIES` can name further imported targets of the package's own dependencies. Linking the one name pulls in that whole chain, which is impossible to express reliably with a flat list of paths: - the consumer does not need to know what the package depends on; - a new dependency added by the package's next release reaches every consumer without a change on their side; - per-configuration variants such as `IMPORTED_LOCATION_DEBUG` let a multi-configuration build link the matching library for each configuration. ## pkg-config packages Libraries that ship only a `.pc` file can still be consumed as a target. The `FindPkgConfig` module's `pkg_check_modules` takes an `IMPORTED_TARGET` keyword that creates `PkgConfig::<prefix>`: ```cmake find_package(PkgConfig REQUIRED) pkg_check_modules(SODIUM REQUIRED IMPORTED_TARGET libsodium) target_link_libraries(app PRIVATE PkgConfig::SODIUM) ``` Without `IMPORTED_TARGET` you get only `SODIUM_INCLUDE_DIRS`, `SODIUM_LIBRARIES` and similar variables, with the same drawbacks as above. ## In practice - Prefer the target a package documents (`ZLIB::ZLIB`, `GTest::gtest`, `Threads::Threads`) over its variables. - Use the variables only for information a target cannot carry, such as `ZLIB_VERSION` in a message or a version check. - When a dependency offers no target at all, wrap the paths in your own `INTERFACE IMPORTED` target once, so the rest of the project still links a single name.

  • What does an imported target store about the library on disk?
    The file itself in `IMPORTED_LOCATION`, or in per-configuration variants such as `IMPORTED_LOCATION_RELEASE` and `IMPORTED_LOCATION_DEBUG`, plus, for a Windows DLL, the import library in `IMPORTED_IMPLIB`. Consumer requirements sit in `INTERFACE_*` properties. CMake generates no build rules for it; it only describes existing files.
  • A find_package call in one subdirectory creates a target that a sibling directory cannot link. Why, and what fixes it?
    Imported targets are scoped to the directory that created them and its subdirectories. Move the `find_package` call up to a common parent, or pass `GLOBAL` (or set `CMAKE_FIND_PACKAGE_TARGETS_GLOBAL`, both since CMake 3.24) so the imported targets become global.

  • Imported targets are only for libraries built elsewhere in the same project
  • ZLIB_LIBRARIES and ZLIB::ZLIB behave identically, so the choice is cosmetic
  • A misspelled ZLIB::ZLIB just links nothing, like an empty variable
  • An imported target found in a subdirectory is visible everywhere automatically
  • pkg-config libraries can only be used through include and library variables