CMake Cookbook
上QQ阅读APP看书,第一时间看更新

There is more

To summarize, when discovering packages there are four available routes:

  1. Use the CMake files <package>Config.cmake<package>ConfigVersion.cmake, and <package>Targets.cmake provided by the package vendor and installed alongside the package itself in standard locations.
  2. Use a find-module for the desired package, whether shipped by CMake or a third party.
  3. Resort to pkg-config, as shown in this recipe.
  4. If none of these are viable, write your own find-module.

The four alternative routes have been ranked by relevance, but each approach has its challenges.

Not all package vendors provide CMake discovery files, but it is becoming more common. This is due to the fact that exporting CMake targets makes it very easy for third-party code to consume additional dependencies imposed by libraries and/or programs that it depends on.

Find-modules have been the workhorse of dependency location in CMake since the very beginning. However, most of them still rely on setting variables consumed by the dependent, such as Boost_INCLUDE_DIRS, PYTHON_INTERPRETER, and so forth. This approach makes it difficult to redistribute your own package for third-parties and ensure that your dependencies are consistently met.

The approach using pkg-config can work very well since it has become a de facto standard for Unix-based systems. For this reason, however, it is not a fully cross-platform approach. Moreover, as the CMake documentation states, in some cases, the user can accidentally override package detection and lead pkg-config to supply incorrect information.

The very last resort is then to write your own find-module CMake script, as we have done in this recipe. This is doable and relies on the FindPackageHandleStandardArgs.cmake module we briefly discussed. However, writing a fully comprehensive find-module is far from trivial; there are many corner cases that are hard to discover, and we have shown an example of that when looking for the ZeroMQ library files on Unix and Windows platforms.

These concerns and difficulties are very well-known to all software developers, as witnessed by the lively discussions on the CMake mailing list: https://cmake.org/pipermail/cmake/2018-May/067556.htmlpkg-config is accepted among Unix package developers, but it cannot be easily ported to not-Unix platforms. CMake configuration files are powerful, but not all software developers are familiar with the CMake syntax. The Common Package Specification project is a very recent attempt at unifying the pkg-config and CMake configuration files approaches for package discovery. You can find more information on the project's website: https://mwoehlke.github.io/cps/

In Chapter 10, Writing an Installer, we will discuss how to make your own package discoverable to third-party applications by using the first route outlined in the previous discussion: providing your own CMake discovery files alongside your project.