How to Find Installed Packages II

Let's learn how to find installed package targets in CMake.

In most cases, we can expect some variables to be set when we call find_package(), whether we're using a built-in find-module or a config-file bundled with a package (assuming that the package was found):

  • <PKG_NAME>_FOUND

  • <PKG_NAME>_INCLUDE_DIRS or <PKG_NAME>_INCLUDES

  • <PKG_NAME>_LIBRARIES or <PKG_NAME>_LIBS

  • <PKG_NAME>_DEFINITIONS

  • IMPORTED targets specified by the find-module or config-file

The IMPORTED targets

The last point is really interesting—if a package supports so-called "modern CMake" (built around targets), it will provide those IMPORTED targets instead (or alongside) of these variables, which allows for cleaner, simpler code. It is recommended to prioritize targets over variables.

Protobuf is a great example, as it offers both variables and IMPORTED targets: protobuf::libprotobuf, protobuf::libprotobuf-lite, protobuf::libprotoc, and protobuf::protoc. This allows us to write even more concise code:

Get hands-on with 1400+ tech skills courses.