# CMake for Boost Developers ## Header-only Libraries ### Automatic Generation with Boostdep The easiest way to add CMake support to a header-only Boost library is to generate a `CMakeLists.txt` file with [Boostdep](https://www.boost.org/doc/libs/release/tools/boostdep/doc/html/index.html) using the command `boostdep --cmake `, where `` is the name of the repository (or the directory name). For example, a `CMakeLists.txt` file for Boost.Core can be generated with `boostdep --cmake core`, and the result will be, as of this writing, ``` # Generated by `boostdep --cmake core` # Copyright 2020 Peter Dimov # Distributed under the Boost Software License, Version 1.0. # https://www.boost.org/LICENSE_1_0.txt cmake_minimum_required(VERSION 3.5...3.16) project(boost_core VERSION "${BOOST_SUPERPROJECT_VERSION}" LANGUAGES CXX) add_library(boost_core INTERFACE) add_library(Boost::core ALIAS boost_core) target_include_directories(boost_core INTERFACE include) target_link_libraries(boost_core INTERFACE Boost::assert Boost::config Boost::static_assert ) if(BUILD_TESTING AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/test/CMakeLists.txt") add_subdirectory(test) endif() ``` Most header-only libraries require no modification to this `boostdep` output. You are not required to use this exact file, but if you can, there are benefits for doing so: * You can regenerate the file at any time, to pick up style changes as the Boost CMake infrastructure evolves and Boostdep is updated to match; * Boostdep computes the library dependencies automatically (as this is its primary purpose as a tool), and if you make changes to the library that cause its dependencies to change, a simple regeneration can keep the list up to date; * You can add a CI job that compares the output of Boostdep to your current CMakeLists.txt file, which will inform you if the file needs to be regenerated. Even if you decide to make changes to your `CMakeLists.txt` file, the generated output provides a useful starting point. Its contents are explained below. ### Version Requirement ``` cmake_minimum_required(VERSION 3.5...3.16) ``` This directive sets the minimum required version of CMake and must be the first thing in it. If CMake is older than 3.5, the result will be a fatal error at configure time, and inability to proceed with building. In addition, this number changes the behavior of newer CMake versions to attempt to be compatible with the stated version. If this only said ``` cmake_minimum_required(VERSION 3.5) ``` a newer version of CMake would have emulated version 3.5. The additional `...3.16` suffix, however, requests newer versions to emulate 3.16 instead. This is typically the latest version of CMake with which the `CMakeLists.txt` file has been tested. If you make changes to the file for other reasons, you may want to update the directive to, say, ``` cmake_minimum_required(VERSION 3.5...3.20) ``` You should avoid increasing the minimal CMake requirement above the Boost minimum, which is at present tentatively and conservatively set to 3.5, but will likely be increased in the near future. If you use a higher minimum, configuring Boost will fail with earlier CMake versions, even if the user is not interested in your library. He will then be forced to manually exclude your library from the build with `-DBOOST_EXCLUDE_LIBRARIES`, which is not an ideal user experience. ### Project Declaration ``` project(boost_core VERSION "${BOOST_SUPERPROJECT_VERSION}" LANGUAGES CXX) ``` The project declaration must generally be preceded only by the above version requirement directive, and sets the project name, the project version and the languages (C, C++) that the source files will use. Boost projects by convention are named `boost_libname`, in lowercase, as in the above. (Libraries in `numeric` such as `numeric/conversion` use an underscore in place of the slash: `boost_numeric_conversion`.) The version is set to match the variable `BOOST_SUPERPROJECT_VERSION`, which the Boost superproject `CMakeLists.txt` file sets to the current Boost version (such as `1.77.0`.) If your library is included directly in a user project with `add_subdirectory`, `BOOST_SUPERPROJECT_VERSION` will not be set and the project version will be empty, as if it weren't given: ``` project(boost_core LANGUAGES CXX) ``` This is usually what one wants. Since manually maintaining a version is time consuming and doesn't bring much, most libraries that do include one fail to maintain it properly. It's better to leave it empty; the version is of no significance in an `add_subdirectory` workflow. The `LANGUAGES` portion should be left at the default `CXX`, which enables the C++ language. If removed, CMake will configure both C and C++. C is only needed if the library has C source files, which a header-only library does not. ### Library Target Declaration ``` add_library(boost_core INTERFACE) ``` The first `add_library` declares the library target, which by convention is `boost_libname`, same as the project name. `INTERFACE` means that this library is header-only and requires no building. ``` add_library(Boost::core ALIAS boost_core) ``` The second `add_library` declares an alternative name for the library, which by convention is `Boost::libname`. It's a good CMake practice to only link to targets of this form (more specifically, to targets containing `::`), because they are unambiguously CMake target names, whereas the alphanumeric `boost_core` may refer to either a target or to a library on disk named f.ex. `libboost_core.so`. ### Include Directory Declaration ``` target_include_directories(boost_core INTERFACE include) ``` This directive declares the directory containing the library headers, which for Boost libraries is the `include` subdirectory. (A relative path is interpreted as relative to `CMAKE_CURRENT_SOURCE_DIR`, that is, to the location of the current `CMakeLists.txt` file.) If you are familiar with CMake, your first impulse would be to declare this line wrong, and replace it with ``` target_include_directories(boost_core INTERFACE $) ``` or perhaps ``` target_include_directories(boost_core INTERFACE $) ``` You shouldn't; the line is, in fact, correct. The Boost superproject will automatically invoke `boost_install` for your target, which will patch the value of the include path to something like that last alternative (but it will take into account the Boost-specific variables `BOOST_INSTALL_INCLUDEDIR` and `BOOST_INSTALL_LAYOUT`.) ### Dependencies ``` target_link_libraries(boost_core INTERFACE Boost::assert Boost::config Boost::static_assert ) ``` Traditionally, Boost has had all the headers copied (in a release) or linked (in a modular layout) into a single `boost/` directory. This made it possible to include headers from any library (A) into any other (B), without the need to declare that B depends on A. With CMake, we will no longer maintain a single `boost/` directory where all the headers are copied. Headers of A will remain in `libs/A/include`, and if this directory isn't in the include path of B, B will not be able to include a header from A. In order for the include path of B to contain `libs/A/include`, B must explicitly declare a dependency on A. In CMake, this is accomplished by "linking" to A, even when A is header-only. This is the purpose of the `target_link_libraries` directive above. In this specific case, it declares that `boost_core` depends on `Boost::assert`, `Boost::config`, and `Boost::static_assert`, and will result into `libs/assert/include`, `libs/config/include`, and `libs/static_assert/include` being added to the include path of Core. (More precisely, they will be added to the include paths of the users of `Boost::core`. Core itself needs no include path because it doesn't require any compilation. This is what the `INTERFACE` keyword means - it sets the "usage requirements" of the target, which are propagated upwards to its users.) The exact form of the directive, with each `Boost::libname` target on its own line, with nothing else, is significant. (In particular, the closing parenthesis should not be placed on the same line as the last target.) This requirement is imposed by the behavior of the user-settable `BOOST_INCLUDE_LIBRARIES` option of the superproject, which requests only the listed libraries and their dependencies to be configured, built, and/or installed. To determine the dependencies, a simple-minded parser scans the `CMakeLists.txt` files, looking for strings matching `Boost::libname` on their own line. ### Testing Support ``` if(BUILD_TESTING AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/test/CMakeLists.txt") add_subdirectory(test) endif() ``` The final portion of the generated `CMakeLists.txt` file adds support for invoking the library tests from the Boost superproject. Since not all libraries have one, this is only enabled when `libs/libname/test/CMakeLists.txt` exists. In principle, since you know whether this file exists for your library or not, you can either remove this condition or remove this entire section; but doing so will make your `CMakeLists.txt` file not match the generated output, which has its downsides. `BUILD_TESTING` is the standard CMake option (typically defined by the `CTest` CMake module) that allows the user to enable or disable tests for a project. It's used here to skip the inclusion of the `test` subproject in order to speed up the configure and build phases of Boost when testing is not required or desired. If your library has a `test/CMakeLists.txt` file that is not intended to be used from the Boost superproject, and is incompatible with it, replace this block with either ``` if(BUILD_TESTING AND CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR) add_subdirectory(test) endif() ``` when your test suite is only intended to be used when your library is the root project (that's usually the case, so this option is the recommended one), or ``` if(BUILD_TESTING AND NOT BOOST_SUPERPROJECT_VERSION) add_subdirectory(test) endif() ``` when your test suite is also intended to be invoked when your library is a subproject of a user project. (This case is rare and user projects are typically not interested in running their subprojects' tests, so you probably don't want this.) ### Installation Support You may have noticed by now that no installation support is declared in the `CMakeLists.txt` file. Nevertheless, the library can in fact be installed. The Boost superproject automatically adds the necessary support to libraries which declare a target `boost_libname` that matches the directory of the `CMakeLists.txt` file (`libs/libname`) and whose `target_include_directories` directive matches the one above. It is recommended that you don't attempt to add your own installation support. Let the superproject handle it. ### Required C++ Standard If your library needs C++11 or above, you can declare this requirement by adding the following directive: ``` target_compile_features(boost_libname INTERFACE cxx_std_11) ``` (use `cxx_std_14` for C++14, `cxx_std_17` for C++17, and so on.) ### Additional Functionality This is all you need to have a header-only library that integrates into the Boost CMake infrastructure. It is also a well-behaved suproject that can be included into user CMake projects via `add_subdirectory`. Avoid the urge to add more functionality unless it's really necessary, as it will compromise the usability of your library as a subproject. Many library authors who use CMake, however, add development-centric functionality to their `CMakeLists.txt` file; you might already have. In this case, try to keep the `CMakeLists.txt` portions described so far as close to unchanged as possible, and at the end, add a section guarded with ``` if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR) # Functionality enabled only when we're the root project endif() ``` and put all your current developer-centric functionality there. This way, subproject use will be unaffected, and you can still use CMake from your library directory for development-related activities such as generating Visual Studio workspaces, or testing outside the Boost tree. ## Compiled Libraries ### A Starting Point Even if your library requires compilation, you can still use `boostdep --cmake libname` at least as a starting point. We'll take Timer as an example, with the output of `boostdep --cmake timer` given below: ``` # Generated by `boostdep --cmake timer` # Copyright 2020 Peter Dimov # Distributed under the Boost Software License, Version 1.0. # https://www.boost.org/LICENSE_1_0.txt cmake_minimum_required(VERSION 3.5...3.16) project(boost_timer VERSION "${BOOST_SUPERPROJECT_VERSION}" LANGUAGES CXX) add_library(boost_timer src/auto_timers_construction.cpp src/cpu_timer.cpp ) add_library(Boost::timer ALIAS boost_timer) target_include_directories(boost_timer PUBLIC include) target_link_libraries(boost_timer PUBLIC Boost::config Boost::core Boost::system PRIVATE Boost::chrono Boost::io Boost::predef Boost::throw_exception ) target_compile_definitions(boost_timer PUBLIC BOOST_TIMER_NO_LIB PRIVATE BOOST_TIMER_SOURCE ) if(BUILD_SHARED_LIBS) target_compile_definitions(boost_timer PUBLIC BOOST_TIMER_DYN_LINK) else() target_compile_definitions(boost_timer PUBLIC BOOST_TIMER_STATIC_LINK) endif() if(BUILD_TESTING AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/test/CMakeLists.txt") add_subdirectory(test) endif() ``` We won't be repeating the explanations of the sections that match the header-only case, and will only focus on the differences. ### Source Files ``` add_library(boost_timer src/auto_timers_construction.cpp src/cpu_timer.cpp ) ``` For a compiled library, you need to declare your source files. This is accomplished by listing them in the `add_library` directive. `boostdep` uses the contents of your `src` subdirectory (but ignores any subdirectories.) Since Timer is a simple library, this works as-is. Many compiled libraries however might require adjusting the source file list, or choosing it based on the platform. For example, Thread needs something like ``` if(BOOST_THREAD_THREADAPI STREQUAL win32) set(THREAD_SOURCES src/win32/thread.cpp src/win32/tss_dll.cpp src/win32/tss_pe.cpp src/win32/thread_primitives.cpp src/future.cpp ) else() set(THREAD_SOURCES src/pthread/thread.cpp src/pthread/once.cpp src/future.cpp ) endif() add_library(boost_thread ${THREAD_SOURCES}) ``` The logic for choosing the source files is already spelled out in your `Jamfile`, so you will need to port it to CMake. If your library has C source files, you'll need to also enable C as a language in your project declaration: ``` project(boost_container VERSION "${BOOST_SUPERPROJECT_VERSION}" LANGUAGES C CXX) ``` although `boostdep` might already have done so for you. The `add_library(libname sources...)` declaration generates either a static or a shared library depending on whether `BUILD_SHARED_LIBS` is set to `ON` or `OFF`. This is idiomatic CMake behavior and is what we want. ### Directive Scope ``` target_include_directories(boost_timer PUBLIC include) ``` The only difference with the header-only case is the use of `PUBLIC` instead of `INTERFACE`. `PUBLIC` applies to both the library and its dependents; in `b2` terms it declares both a requirement and a usage-requirement. ``` target_link_libraries(boost_timer PUBLIC Boost::config Boost::core Boost::system PRIVATE Boost::chrono Boost::io Boost::predef Boost::throw_exception ) ``` Again, the difference here is in the use of the scope keywords `PUBLIC` and `PRIVATE` (applies only to the library, not to dependents) instead of `INTERFACE`. `boostdep` puts the dependencies referred to from the `include` subdirectory in the `PUBLIC` section, and those referred to from the `src` subdirectory in the `PRIVATE` section. ### Compile Definitions ``` target_compile_definitions(boost_timer PUBLIC BOOST_TIMER_NO_LIB PRIVATE BOOST_TIMER_SOURCE ) ``` The compile definitions are passed to the compiler with a `-D` option and define macros. In this case by Boost convention we define `BOOST_TIMER_NO_LIB` to disable autolink and `BOOST_TIMER_SOURCE` when compiling the library to properly declare exported functions as exported (as opposed to imported, which will be the case when using the library.) ``` if(BUILD_SHARED_LIBS) target_compile_definitions(boost_timer PUBLIC BOOST_TIMER_DYN_LINK) else() target_compile_definitions(boost_timer PUBLIC BOOST_TIMER_STATIC_LINK) endif() ``` When building shared libraries, we define `BOOST_TIMER_DYN_LINK`, and when building static libraries, we define `BOOST_TIMER_STATIC_LINK`. Again, this is needed to property export and import functions from dynamic libraries, in particular on the Windows platform. These defines are described in the [Boost document about separate compilation](https://www.boost.org/development/separate_compilation.html) and you look at how [the Timer library uses them](https://github.com/boostorg/timer/blob/e9387e4d9956074dffcc15bf15bd6d2625e91ebf/include/boost/timer/config.hpp) as an example. ### Building More Than One Library Target If your build results in more than one library being built, or if the name of your library target does not match your directory name, you need to invoke the installation support manually. As an example, Serialization builds two library targets, `boost_serialization` and `boost_wserialization`, and the procedure to install them entails adding [the following section](https://github.com/boostorg/serialization/blob/337b3fbc7c4648d6f95f863546b9482500c8dec5/CMakeLists.txt#L116-L118) to `CMakeLists.txt`: ``` if(BOOST_SUPERPROJECT_VERSION AND NOT CMAKE_VERSION VERSION_LESS 3.13) boost_install(TARGETS boost_serialization boost_wserialization VERSION ${BOOST_SUPERPROJECT_VERSION} HEADER_DIRECTORY include) endif() ``` The check for `BOOST_SUPERPROJECT_VERSION` is necessary because without the superproject, `boost_install` is not available. The check for the CMake version is needed because the automatic Boost installation support requires CMake 3.13. Even though `boost_install` will work on earlier CMake versions, you will likely get errors at generate time because the dependencies of your library will lack install support. For another example of `CMakeLists.txt` files building and installing more than one library, see [Boost.Test](https://github.com/boostorg/test/blob/efaa7018bf19826ca282e28a11a2f7db72af7930/CMakeLists.txt).