Creating Reusable Packages

Let's learn how to turn our project into a natively available package for other CMake projects.

We have used find_package() extensively. We saw how convenient it is and how it simplifies the whole process. To make our project accessible through this command, we need to complete a few steps so that CMake can treat our project as a coherent package:

  • Make our targets relocatable.

  • Install the target export file to a standard location.

  • Create a config-files and version file for the package.

Let's start from the beginning: why do targets need to be relocatable, and how can we do this?

Understanding the issues with relocatable targets

Installation solves many problems, but unfortunately, it also introduces some complexity: not only is CMAKE_INSTALL_PREFIX platform-specific, but it can also be set by the user at the installation stage with the --prefix option. However, target export files are generated before the installation and during the build stage, at which point we don't know where the installed artifacts will go. Take a look at the following code:

Get hands-on with 1400+ tech skills courses.