Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
CMake Cookbook
CMake Cookbook

CMake Cookbook: Building, testing, and packaging modular software with modern CMake

Arrow left icon
Profile Icon Bast Profile Icon Di Remigio
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.2 (9 Ratings)
Paperback Sep 2018 606 pages 1st Edition
eBook
€24.99 €36.99
Paperback
€45.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Bast Profile Icon Di Remigio
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.2 (9 Ratings)
Paperback Sep 2018 606 pages 1st Edition
eBook
€24.99 €36.99
Paperback
€45.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€24.99 €36.99
Paperback
€45.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

CMake Cookbook

Setting up Your System

Before diving into CMake and the recipes in this book, you will need to set your system up to successfully run all of the examples. In this section, we will discuss the following topics:

  1. How to obtain the code for the recipes
  2. How to install all of the tools required to run the code samples on GNU/Linux, macOS, and Windows
  3. How the automated testing for the repository works
  4. How to report problems with the recipes and suggest improvements

We have strived to make our discussions of the topics in this book as accessible to novices as possible. However, this book does not start from absolute scratch. We assume that you have basic knowledge of the native tools for building software that are available on your platform of choice. It is also helpful (but not required) to have basic experience with version control using Git, to interact with the repository holding the recipe sources.

Obtaining the code

The source code for the recipes in this book is available on GitHub, at https://github.com/dev-cafe/cmake-cookbook. The code is licensed under the standard open source MIT license: this is a permissive software license, and you can reuse and remix the code in whatever way you see fit, as long as the original copyright and license notice are included in any copies of the software/source. The full text of the license is available at https://opensource.org/licenses/MIT.

In order to test the recipes by yourself, you will need a working installation of Git, obtained as follows:

  • All major GNU/Linux distributions offer Git prepackaged, via their package managers. If that is not your case, a binary distribution can be downloaded from the Git project website at https://git-scm.com.
  • On macOS, it is possible to use Homebrew or MacPorts to install Git.
  • On Windows, you can download the Git executable from the Git project website at https://git-scm.com.

Alternatively, you can access the examples with the GitHub desktop client at https://desktop.github.com.

Yet another alternative is to download and extract the ZIP file from https://github.com/dev-cafe/cmake-cookbook.

Once you have Git installed, you can clone the repository to your local machine, as follows:

$ git clone https://github.com/dev-cafe/cmake-cookbook.git

This will create a folder named cmake-cookbook. The book and the repository are organized in chapters and recipes. The numbering of chapters and the order of recipes in the repository reflect the order in the text. Each recipe is further organized into example folders. Some of the recipes have more than one example, usually when similar CMake concepts are illustrated in different programming languages.

The recipes are tested on GNU/Linux, macOS, and Windows, using state-of-the-art continuous integration services. We will discuss the testing set up shortly.

We have tagged the precise versions that correspond to the examples printed in this book with the tag v1.0. For maximum overlap with the book text, you can fetch this particular version as follows:

$ git clone --single-branch -b v1.0 https://github.com/dev-cafe/cmake-cookbook.git

We expect to receive bug fixes and the GitHub repository to evolve. To get the latest updates, you may prefer to follow the master branch of the repository, instead.

Docker image

You will likely find that the easiest approach to testing the book's recipes in a software environment (which contains all of the dependencies preinstalled) is to use a Docker image that we have set up, based on Ubuntu 18.04. You can install Docker on your favorite operating system, following the official documentation at https://docs.docker.com.

Once Docker is installed, you can run our image and test the recipes with the full software environment in place, as follows:

$ docker run -it devcafe/cmake-cookbook_ubuntu-18.04
$ git clone https://github.com/dev-cafe/cmake-cookbook.git
$ cd cmake-cookbook
$ pipenv install --three
$ pipenv run python testing/collect_tests.py 'chapter-*/recipe-*'

Installing prerequisite software

An alternative to running the book recipes in a container is to install the dependencies directly on the host operating system. For this, we have assembled a minimal toolstack that can be used as a basic starting point for all of our recipes. You will have to install the following:

  1. CMake
  2. Language-specific tools, that is, the compilers
  3. Build automation tools
  4. Python

We will also detail how to install the additional dependencies required by some of the recipes.

Getting CMake

CMake 3.5 is the minimum required version of CMake for this book. Only a few, specific recipes and examples that demonstrate useful features that were introduced after version 3.5 will require a more recent version of CMake. The introduction to every recipe features an info box, pointing out where the code is available, which examples are given, and the minimum version of CMake required. The info boxes will look like the following box:

The code for this recipe is available at https://github.com/dev-cafe/cmake-cookbook/tree/v1.0/chapter-03/recipe-10, and includes a C example. The recipe is valid with CMake version 3.5 (and higher) and has been tested on GNU/Linux, macOS, and Windows.

Some, if not most, of the recipes will still be valid with older versions of CMake. However, we have made no attempts to test this assumption, since we consider CMake 3.5 to be the default on most systems and distributions. We also consider upgrading to later versions of CMake to be a straightforward step.

CMake can be installed in a number of different ways. Downloading and extracting the binary distribution maintained by Kitware will work across all platforms. The download page is at https://cmake.org/download/.

Most GNU/Linux distributions have CMake available in their package managers. However, on some distributions, the packaged version can be rather old, so downloading the binary maintained by Kitware is still the preferred option. The following commands will download and install CMake 3.5.2 under $HOME/Deps/cmake (adjust this path to your preference), from the version packaged by CMake:

$ cmake_version="3.5.2"
$ target_path=$HOME/Deps/cmake/${cmake_version}
$ cmake_url="https://cmake.org/files/v${cmake_version%.*}/cmake-${cmake_version}-Linux-x86_64.tar.gz"
$ mkdir -p "${target_path}"
$ curl -Ls "${cmake_url}" | tar -xz -C "${target_path}" --strip-components=1
$ export PATH=$HOME/Deps/cmake/${cmake_version}/bin${PATH:+:$PATH}
$ cmake --version

Homebrew for macOS reliably ships the latest version of CMake:

$ brew upgrade cmake

On Windows, you can use Visual Studio 2017, which provides CMake support. The installation of Visual Studio 2017 is documented in Chapter 13, Alternative Generators and Cross-compilation, Recipe 1, Building a CMake project using Visual Studio 2017.

Alternatively, you can download the MSYS2 installer from https://www.msys2.org , follow the instructions given therein to update the list of packages, and then install CMake using the package manager, pacman. The following code assumes that we are building the 64-bit version:

$ pacman -S mingw64/mingw-w64-x86_64-cmake

For the 32-bit version, use the following (though we will only refer to 64-bit versions in future, for the sake of brevity):

$ pacman -S mingw64/mingw-w64-i686-cmake

Another nice feature of MSYS2 is that it provides a terminal on Windows that feels and behaves like a terminal on a Unix-like operating system, providing a useful development environment.

Compilers

We will need compilers for C++, C, and Fortran. These should be fairly recent, as we require support for recent language standards in most of the recipes. CMake offers very good support for many compilers, from both commercial and non-commercial vendors. To keep the recipes consistently cross-platform and as operating system independent as possible, we have worked with open source compilers:

  • On GNU/Linux, the GNU Compiler Collection (GCC) is the obvious choice. It is free and available for all distributions. For example, on Ubuntu, you can install the compilers as follows:
$ sudo apt-get install g++ gcc gfortran 
  • Clang, in the LLVM family, is also a good choice for C++ and C:
$ sudo apt-get install clang clang++ gfortran
  • On macOS, the LLVM compilers shipped with XCode will work for C++ and C. We have used the Fortran compiler from GCC in our macOS testing. This has to be installed separately, using the package manager. For example, the command for Homebrew is as follows:
$ brew install gcc
  • On Windows, you can use Visual Studio for the C++ and C recipes. Alternatively, you can use the MSYS2 installer and install the entire toolchain, including a C++, C, and Fortran compiler, with the following single command in an MSYS2 environment (for the 64-bit version):
$ pacman -S mingw64/mingw-w64-x86_64-toolchain

Build-automation tools

These build-automation tools will provide the infrastructure for building and linking the projects presented in the recipes. What you will end up installing and using strongly depends on your operating system and your taste:

  • On GNU/Linux, GNU Make will most likely be installed automatically, when installing the compilers.
  • On macOS, XCode will provide GNU Make.
  • On Windows, Visual Studio will provide you with the complete infrastructure. In the MSYS2 environment, GNU Make is installed as a part of the mingw64/mingw-w64-x86_64-toolchain package, which we installed previously.

For maximum portability, we have made the recipes as agnostic about these system-dependent details as possible. A clear advantage of this approach is that configuring, building, and linking are native to each platform and each set of compilers.

The Ninja program is a different build-automation tool that works on GNU/Linux, macOS, and Windows. Ninja is a new build tool, with a focus on speed, especially for incremental rebuilds. Prepackaged binaries for GNU/Linux, macOS, and Windows can be found on the project's GitHub repository at https://github.com/ninja-build/ninja/releases.

Using CMake and Ninja with Fortran projects requires some care. CMake 3.7.2 or later is required, along with the version of Ninja maintained by Kitware, available at https://github.com/Kitware/ninja/releases.

On GNU/Linux, you can install Ninja with the following series of commands:

$ mkdir -p ninja
$ ninja_url="https://github.com/Kitware/ninja/releases/download/v1.8.2.g3bbbe.kitware.dyndep-1.jobserver-1/ninja-1.8.2.g3bbbe.kitware.dyndep-1.jobserver-1_x86_64-linux-gnu.tar.gz"
$ curl -Ls ${ninja_url} | tar -xz -C ninja --strip-components=1
$ export PATH=$HOME/Deps/ninja${PATH:+:$PATH}

On Windows, using the MSYS2 environment (assuming the 64-bit version), executing the command:

$ pacman -S mingw64/mingw-w64-x86_64-ninja
We recommend reading the essay at http://www.aosabook.org/en/posa/ninja.html for an enlightening discussion of Ninja's history and design choices.

Python

This book is about CMake, but some of the recipes, along with the whole infrastructure powering testing, need Python. Thus, first and foremost, you will need a working installation of Python: the interpreter, header files, and libraries. The end of life for Python 2.7 was announced for 2020, and we will thus use Python 3.5.

On Ubuntu 14.04 LTS (this is the environment used by Travis CI which we will discuss later on), Python 3.5 can be installed as follows:

$ sudo apt-get install python3.5-dev

On Windows, using the MSYS2 environment, the Python environment can be installed as follows (assuming the 64-bit version):

$ pacman -S mingw64/mingw-w64-x86_64-python3
$ pacman -S mingw64/mingw-w64-x86_64-python3-pip
$ python3 -m pip install pipenv

Specific Python modules are also required, in order to run the testing machinery that we have put in place. These can be installed system-wide by using your favorite package manager, or in an isolated environment. The latter approach is highly recommended, as it offers the following advantages:

  • You can install packages and clean up installations without affecting the system environment.
  • Packages can be installed without administrator privileges.
  • You lower the risk of version and dependency clashes.
  • You gain much better control over package dependencies, for reproducibility.

We have prepared a Pipfile for this purpose. In combination with its Pipfile.lock, you can use Pipenv (http://pipenv.readthedocs.io) to generate an isolated environment, with all packages installed. To create this environment for the recipe example repository, run the following commands in the top-level directory of the repository:

$ pip install --user pip pipenv --upgrade
$ pipenv install --python python3.5

The pipenv shell command will drop you into a command-line environment with the specific version of Python and all of the packages available. Executing exit will bring you back to a clean environment. You can also use pipenv run to directly execute a command within the isolated environment.

Alternatively, the requirements.txt file in the repository can be used, in combination with Virtualenv (http://docs.python-guide.org/en/latest/dev/virtualenvs/) and pip, to achieve the same effect:

$ virtualenv --python=python3.5 venv
$ source venv/bin/activate
$ pip install -r requirements.txt

The virtual environment can be exited by using the deactivate command.

Yet another alternative is to use Conda environments. To do so, we suggest installing Miniconda. The following instructions will install the latest Miniconda to the directory $HOME/Deps/conda, for GNU/Linux (download from https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh) or macOS (download from https://repo.continuum.io/miniconda/Miniconda3-latest-MacOSX-x86_64.sh):

$ curl -Ls https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh > miniconda.sh
$ bash miniconda.sh -b -p "$HOME"/Deps/conda &> /dev/null
$ touch "$HOME"/Deps/conda/conda-meta/pinned
$ export PATH=$HOME/Deps/conda/bin${PATH:+:$PATH}
$ conda config --set show_channel_urls True
$ conda config --set changeps1 no
$ conda update --all
$ conda clean -tipy

On Windows, you can download the latest Miniconda from https://repo.continuum.io/miniconda/Miniconda3-latest-Windows-x86_64.exe. The package can be installed using PowerShell, as follows:

$basedir = $pwd.Path + "\"
$filepath = $basedir + "Miniconda3-latest-Windows-x86_64.exe"
$Anaconda_loc = "C:\Deps\conda"
$args = "/InstallationType=JustMe /AddToPath=0 /RegisterPython=0 /S /D=$Anaconda_loc"
Start-Process -FilePath $filepath -ArgumentList $args -Wait -Passthru

$conda_path = $Anaconda_loc + "\Scripts\conda.exe"
$args = "config --set show_channel_urls True"
Start-Process -FilePath "$conda_path" -ArgumentList $args -Wait -Passthru
$args = "config --set changeps1 no"
Start-Process -FilePath "$conda_path" -ArgumentList $args -Wait -Passthru
$args = "update --all"
Start-Process -FilePath "$conda_path" -ArgumentList $args -Wait -Passthru
$args = "clean -tipy"
Start-Process -FilePath "$conda_path" -ArgumentList $args -Wait -Passthru

Once Conda is installed, the Python modules can be installed as follows:

$ conda create -n cmake-cookbook python=3.5
$ conda activate cmake-cookbook
$ conda install --file requirements.txt

Executing conda deactivate will drop you outside of the isolated environment.

Additional software

Some recipes will require additional software, which will be covered in the following sections.

BLAS and LAPACK

Most Linux distributions provide packages for BLAS and LAPACK. For example, on Ubuntu 14.04 LTS, you can run the following:

$ sudo apt-get install libatlas-dev liblapack-dev liblapacke-dev

On macOS, the Accelerate libraries, shipped with XCode, are enough for our purposes.

On Windows, using the MSYS2 environment, these libraries can be installed as follows (assuming the 64-bit version):

$ pacman -S mingw64/mingw-w64-x86_64-openblas

Alternatively, you can download the reference implementation of BLAS and LAPACK from GitHub (https://github.com/Reference-LAPACK/lapack) and compile the libraries from sources. Commercial vendors might offer packages for their own implementations of the BLAS and LAPACK APIs, available as installers for your platform.

Message passing interface (MPI)

There are many commercial and non-commercial implementations of MPI. For our introductory purposes, it is enough to install any of the freely available non-commercial implementations. On Ubuntu 14.04 LTS, we recommend OpenMPI. It can be installed with the following command:

$ sudo apt-get install openmpi-bin libopenmpi-dev

For macOS, Homebrew distributes MPICH:

$ brew install mpich

It is also possible to compile OpenMPI from the sources publicly available at https://www.open-mpi.org/software/.

For Windows, the Microsoft MPI implementation can be installed via https://msdn.microsoft.com/en-us/library/bb524831(v=vs.85).aspx.

The Eigen linear algebra template library

Some recipes will need the Eigen linear algebra template library, version 3.3 or later. If your package manager does not provide Eigen, you can install it from the online source archive (http://eigen.tuxfamily.org). For example, on GNU/Linux and macOS, you can install Eigen to the directory $HOME/Deps/eigen, as follows:

$ eigen_version="3.3.4"
$ mkdir -p eigen
$ curl -Ls http://bitbucket.org/eigen/eigen/get/${eigen_version}.tar.gz | tar -xz -C eigen --strip-components=1
$ cd eigen
$ cmake -H. -Bbuild_eigen -DCMAKE_INSTALL_PREFIX="$HOME/Deps/eigen" &> /dev/null
$ cmake --build build_eigen -- install &> /dev/null

The Boost libraries

Boost packages are available for every operating system; most Linux distributions have packages available through their package managers. On Ubuntu 14.04 LTS, for instance, the Boost Filesystem, Boost Python, and Boost Test libraries can be installed with the following command:

$ sudo apt-get install libboost-filesystem-dev libboost-python-dev libboost-test-dev

For macOS, both MacPorts and Homebrew provide packages for recent versions of Boost. Our testing setup on macOS installs Boost as follows:

$ brew cask uninstall --force oclint
$ brew uninstall --force --ignore-dependencies boost
$ brew install boost
$ brew install boost-python3

Prebuilt binary distributions for Windows are also available for download from the Boost website at http://www.boost.org. Alternatively, you can download the sources from https://www.boost.org and compile the libraries yourself.

Cross-compilers

On Debian/Ubuntu-like systems, cross-compilers can be installed with the following command:

$ sudo apt-get install gcc-mingw-w64 g++-mingw-w64 gfortran-mingw-w64

On macOS, using Brew, the cross-compilers can be installed as follows:

$ brew install mingw-w64

Other package managers offer corresponding packages.

An alternative to using packaged cross-compilers is to build them from sources, using the M cross environment (https://mxe.cc).

ZeroMQ, pkg-config, UUID, and Doxygen

On Ubuntu 14.04 LTS, these packages can be installed as follows:

$ sudo apt-get install pkg-config libzmq3-dev doxygen graphviz-dev uuid-dev

On macOS, we recommend installing with Brew:

$ brew install ossp-uuid pkg-config zeromq doxygen

The pkg-config program and UUID library are only available on Unix-like systems.

On Windows, using the MSYS2 environment, these dependencies can be installed as follows (assuming the 64-bit version):

$ pacman -S mingw64/mingw-w64-x86_64-zeromq
$ pacman -S mingw64/mingw-w64-x86_64-pkg-config
$ pacman -S mingw64/mingw-w64-x86_64-doxygen
$ pacman -S mingw64/mingw-w64-x86_64-graphviz

Conda build and deployment tools

The recipes exploring packaging with Conda will need Miniconda and the Conda build and deployment tools installed on the system. The instructions for the installation of Miniconda were given previously. To install Conda build and deployment tools on GNU/Linux and macOS, run the following commands:

$ conda install --yes --quiet conda-build anaconda-client jinja2 setuptools
$ conda clean -tipsy
$ conda info -a

These tools can be installed on Windows as follows:

$conda_path = "C:\Deps\conda\Scripts\conda.exe"

$args = "install --yes --quiet conda-build anaconda-client jinja2 setuptools"
Start-Process -FilePath "$conda_path" -ArgumentList $args -Wait -Passthru

$args = "clean -tipsy"
Start-Process -FilePath "$conda_path" -ArgumentList $args -Wait -Passthru

$args = "info -a"
Start-Process -FilePath "$conda_path" -ArgumentList $args -Wait -Passthru

Testing the recipes

The recipes are tested on state-of-the-art continuous integration (CI) services: Travis (https://travis-ci.org) for GNU/Linux and macOS, Appveyor (https://www.appveyor.com) for Windows, and CircleCI (https://circleci.com) for additional GNU/Linux testing with commercial compilers. The configuration files for the CI services can be found in the repository (https://github.com/dev-cafe/cmake-cookbook/): .travis.yml for Travis, .appveyor.yml for Appveyor, and .circleci/config.yml for CircleCI. Additional installation scripts for Travis and Appveyor can be found in the folder testing/dependencies.

We test the recipes with CMake 3.5.2 and CMake 3.12.1 on the Travis GNU/Linux infrastructure. CMake 3.12.1 is used on the Travis macOS infrastructure. On Appveyor, testing uses CMake 3.11.3. On Circle, CMake 3.12.1 is used.

The testing machinery is a set of Python scripts that are also contained in the testing folder. The script collect_tests.py will run tests and report their statuses. Recipes can be tested in isolation, or in batches; collect_tests.py accepts a regular expression as command-line input, for example:

$ pipenv run python testing/collect_tests.py 'chapter-0[1,7]/recipe-0[1,2,5]'

This command will run tests for Recipes 1, 2, and 5, in Chapters 1 and 7. A sample of the output looks as follows:

To get more verbose output, set VERBOSE_OUTPUT=ON:

$ env VERBOSE_OUTPUT=ON pipenv run python testing/collect_tests.py 'chapter-*/recipe-*'

Reporting problems and suggesting improvements

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Learn to configure, build, test, and package software written in C, C++, and Fortran
  • Progress from simple to advanced tasks with examples tested on Linux, macOS, and Windows
  • Manage code complexity and library dependencies with reusable CMake building blocks

Description

CMake is cross-platform, open-source software for managing the build process in a portable fashion. This book features a collection of recipes and building blocks with tips and techniques for working with CMake, CTest, CPack, and CDash. CMake Cookbook includes real-world examples in the form of recipes that cover different ways to structure, configure, build, and test small- to large-scale code projects. You will learn to use CMake's command-line tools and master modern CMake practices for configuring, building, and testing binaries and libraries. With this book, you will be able to work with external libraries and structure your own projects in a modular and reusable way. You will be well-equipped to generate native build scripts for Linux, MacOS, and Windows, simplify and refactor projects using CMake, and port projects to CMake.

Who is this book for?

If you are a software developer keen to manage build systems using CMake or would like to understand and modify CMake code written by others, this book is for you. A basic knowledge of C++, C, or Fortran is required to understand the topics covered in this book.

What you will learn

  • Configure, build, test, and install code projects using CMake
  • Detect operating systems, processors, libraries, files, and programs for conditional compilation
  • Increase the portability of your code
  • Refactor a large codebase into modules with the help of CMake
  • Build multi-language projects
  • Know where and how to tweak CMake configuration files written by somebody else
  • Package projects for distribution
  • Port projects to CMake

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 26, 2018
Length: 606 pages
Edition : 1st
Language : English
ISBN-13 : 9781788470711
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Sep 26, 2018
Length: 606 pages
Edition : 1st
Language : English
ISBN-13 : 9781788470711
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 112.97
The Modern C++ Challenge
€29.99
CMake Cookbook
€45.99
C++ Reactive Programming
€36.99
Total 112.97 Stars icon

Table of Contents

17 Chapters
Setting up Your System Chevron down icon Chevron up icon
From a Simple Executable to Libraries Chevron down icon Chevron up icon
Detecting the Environment Chevron down icon Chevron up icon
Detecting External Libraries and Programs Chevron down icon Chevron up icon
Creating and Running Tests Chevron down icon Chevron up icon
Configure-time and Build-time Operations Chevron down icon Chevron up icon
Generating Source Code Chevron down icon Chevron up icon
Structuring Projects Chevron down icon Chevron up icon
The Superbuild Pattern Chevron down icon Chevron up icon
Mixed-language Projects Chevron down icon Chevron up icon
Writing an Installer Chevron down icon Chevron up icon
Packaging Projects Chevron down icon Chevron up icon
Building Documentation Chevron down icon Chevron up icon
Alternative Generators and Cross-compilation Chevron down icon Chevron up icon
Testing Dashboards Chevron down icon Chevron up icon
Porting a Project to CMake Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.2
(9 Ratings)
5 star 33.3%
4 star 0%
3 star 44.4%
2 star 0%
1 star 22.2%
Filter icon Filter
Top Reviews

Filter reviews by




Esteban May 16, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Llevo varios años usando CMake y quería darle un repaso al 'CMake moderno' para limpiar partes obsoletas de mis proyectos así que me decidí por este libro.Es un buen libro tanto para iniciarse (3 primeros capítulos) como para profundizar en temas más avanzados de CMake. Los tres primeros capítulos abarca lo más básico para comenzar con CMake. Se ve como crear un ejecutable, una librería estática o dinámica, estructuras condicionales, presentación de opciones al usuario, trabajo con librerías de terceros, ...El 4° capítulo va sobre como trabajar con pruebas unitarias. Me parece muy acertado que hayan incluido ejemplos para google test y boost test. También tiene otro ejemplo con Valgrind para detectar problemas de memoría. Aquí hecho de menos que no se haya incluido también Visual Leak Detector.Lo que no me convence es que hayan dejado para el capítulo 7 la estructuración de un proyecto CMake. Personalmente creo que es de las primeras cosas que se debería explicar.Incluye también la instalación, el empaquetado con CPack, documentación con Doxigen y Sphin, CDash.Otro acierto del libro es utilizar en los ejemplos librerías como OpenMP, Eigen, Blas, Lapack o Boost.Todos los ejemplos están en GitHub lo cual es de agradecer.
Amazon Verified review Amazon
David C Sep 07, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The author is modest in calling this book a Cookbook. It is really so much more than that. It is a well-structured tutorial and how-to as well. The recipes build on prior recipes. Everything is explained in detail, including concepts and background about CMake. The author provides a ready-made Docker image with all the needed tools pre-installed, and a Git repository with all the book's example code. You can actually edit, build, and run the examples in the Docker image as you are reading the book. This is very helpful. I was up and running the recipes in about 10 minutes (only because I needed to install Docker on my system - otherwise it would have been 2 minutes!).I am a professional embedded C++ developer who inherited a complex CMake build environment at work, which I need to enhance and modify. I had never been exposed to CMake before. This book is proving to be an extremely valuable resource for me, helping me to understand what I am dealing with and how to modify it.
Amazon Verified review Amazon
Nikita Karatun Oct 08, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Almost everything I've learned about cmake and used in my projects I've learned from this book. That includes but not limited to: projects structure, division to modules, testing, writing custom dependency find routines, windows/linux specifics. One may either go from cover to cover or just pick up necessary recipes from the toc when required.Since I'm transferring from Java to C++ and I've got plenty of books to read now, I have to sacrifice cover to cover reading of this cook book for now but will totally do that once I've got more time.
Amazon Verified review Amazon
User0910 Jun 13, 2021
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Le livre n'est pas vraiment un "livre de recettes" au sens classique, qui présupposerait une certaine connaissance de CMake. C'est bien un livre d'introduction à CMake, mais avec le parti pris d'apprendre à s'en servir en partant d'exemples complets et progressivement plus complexes, plutôt que par une introduction formelle au langage. Ce n'est pas forcément une mauvaise chose, je suppose que c'est une question de goût.Au niveau des bonnes choses, je trouve que le livre contient pas mal de recettes que l'on ne trouvera pas ailleurs, du fait de l'ouverture de l'auteur, très tôt dans le livre, à des projets multi-langages (notamment contenant du python). Sur le papier, le livre va assez loin.Mais, au delà de l'aspect un peu rigide de la présentation imposée par Packt (Getting Ready/How to do it/How it works) qui hache et dilue le propos à mes yeux, le livres souffre de plusieurs défault. Le principal est qu'il est malheureusement déjà dépassé en 2021. CMake a évolué rapidement ces dernières années, trop pour pouvoir recommander à l'achat un livre qui semble se concentrer sur CMake 3.5 alors que CMake 3.20 vient de sortir.Un autre défaut est que l'auteur ne semble malheureusement pas toujours de bon conseil. Non, on ne peut pas laisser traîner un CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS dans un example de son livre sans expliquer tout de suite après que c'est une mauvaise pratique à bannir dans la vraie vie. Si, il est légitime de vouloir utiliser les variables globales CMAKE_<LANG>_FLAGS pour contrôler les flags de compilation de tous les projets, c'est même parfois recommandable. Plus gênant, la recette pour écrire un find module repose sur les vieux mécanismes de CMake 2 en retournant des variables plutôt qu'une target.Enfin, contrairement à ce que l'auteur laisse entendre tout au long du livre, les examples du livres sont très fortement orientés Linux, et certains ne fonctionneront tout simplement pas sous Windows avec Visual Studio. L'utilisation omniprésente de pkg-config, par exemple, est décevante.
Amazon Verified review Amazon
Flash Sheridan Oct 28, 2019
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Not bad, which is the first time I’ve been able to say that for a Packt book.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.