Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
CMake Cookbook
CMake Cookbook

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

eBook
$9.99 $47.99
Paperback
$60.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

CMake Cookbook

From a Simple Executable to Libraries

In this chapter, we will cover the following recipes:

  • Compiling a single source file into an executable
  • Switching generators
  • Building and linking static and shared libraries
  • Controlling compilation with conditionals
  • Presenting options to the user
  • Specifying the compiler
  • Switching the build type
  • Controlling compiler flags
  • Setting the standard for the language
  • Using control flow constructs

Introduction

The recipes in this chapter will walk you through fairly basic tasks needed to build your code: compiling an executable, compiling a library, performing build actions based on user input, and so forth. CMake is a build system generator particularly suited to being platform- and compiler-independent. We have striven to show this aspect in this chapter. Unless stated otherwise, all recipes are independent of the operating system; they can be run without modifications on GNU/Linux, macOS, and Windows.

The recipes in this book are mainly designed for C++ projects and demonstrated using C++ examples, but CMake can be used for projects in other languages, including C and Fortran. For any given recipe and whenever it makes sense, we have tried to include examples in C++, C, and Fortran. In this way, you will be able to choose the recipe in your favorite flavor. Some recipes...

Compiling a single source file into an executable

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

In this recipe, we will demonstrate how to run CMake to configure and build a simple project. The project consists of a single source file for a single executable. We will discuss the project in C++, but examples for C and Fortran are available in the GitHub repository.

Getting ready

We wish to compile the following source code into a single executable:

#include <cstdlib>
#include <iostream>
#include <string...

Switching generators

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

CMake is a build system generator and a single CMakeLists.txt can be used to configure projects for different toolstacks on different platforms. You describe in CMakeLists.txt the operations the build system will have to run to get your code configured and compiled. Based on these instructions, CMake will generate the corresponding instructions for the chosen build system (Unix Makefiles, Ninja, Visual Studio, and so on). We will revisit generators in Chapter 13, Alternative Generators and Cross-compilation.

...

Building and linking static and shared libraries

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

A project almost always consists of more than a single executable built from a single source file. Projects are split across multiple source files, often spread across different subdirectories in the source tree. This practice not only helps in keeping source code organized within a project, but greatly favors modularity, code reuse, and separation of concerns, since common tasks can be grouped into libraries. This separation also simplifies and speeds up recompilation of a project during development. In this recipe, we will show how to group sources into libraries and how...

Controlling compilation with conditionals

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

So far, we have looked at fairly simple projects, where the execution flow for CMake was linear: from a set of source files to a single executable, possibly via static or shared libraries. To ensure complete control over the execution flow of all the steps involved in building a project, configuration, compilation, and linkage, CMake offers its own language. In this recipe, we will explore the use of the conditional construct if-elseif-else-endif.

The CMake language is fairly large and consists of basic control constructs, CMake-specific commands, and infrastructure for modularly extending the...

Presenting options to the user

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

In the previous recipe, we introduced conditionals in a rather rigid fashion: by introducing variables with a given truth value hardcoded. This can be useful sometimes, but it prevents users of your code from easily toggling these variables. Another disadvantage of the rigid approach is that the CMake code does not communicate to the reader that this is a value that is expected to be modified from outside. The recommended way to toggle behavior in the build system generation for your project is to present logical switches as options in your CMakeLists.txt using the option() command. This recipe will show...

Specifying the compiler

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

One aspect that we have not given much thought to so far is the selection of compilers. CMake is sophisticated enough to select the most appropriate compiler given the platform and the generator. CMake is also able to set compiler flags to a sane set of defaults. However, often we wish to control the choice of the compiler, and in this recipe we will show how this can be done. In later recipes, we will also consider the choice of build type and show how to control compiler flags.

How to do it

...

Switching the build type

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

CMake has the notion of build types or configurations, such as Debug, Release, and so forth. Within one configuration, one can collect related options or properties, such as compiler and linker flags, for a Debug or Release build. The variable governing the configuration to be used when generating the build system is CMAKE_BUILD_TYPE. This variable is empty by default, and the values recognized by CMake are:

  1. Debug for building your library or executable without optimization and with debug symbols,
  2. Release for building your library or executable with optimization and without debug symbols,
  3. RelWithDebInfo for...

Controlling compiler flags

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

The previous recipes showed how to probe CMake for information on the compilers and how to tune compiler optimizations for all targets in your project. The latter task is a subset of the general need to control which compiler flags are used in your project. CMake offers a lot of flexibility for adjusting or extending compiler flags and you can choose between two main approaches:

  • CMake treats compile options as properties of targets. Thus, one can set compile options on a per target basis, without overriding CMake defaults.
  • You can directly modify the CMAKE_<LANG>_FLAGS_<CONFIG> variables by using...

Setting the standard for the language

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

Programming languages have different standards available, that is, different versions that offer new and improved language constructs. Enabling new standards is accomplished by setting the appropriate compiler flag. We have shown in the previous recipe how this can be done, either on a per-target basis or globally. With its 3.1 version, CMake introduced a platform- and compiler-independent mechanism for setting the language standard for C++ and C: setting the <LANG>_STANDARD property for targets.

...

Using control flow constructs

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

We have used if-elseif-endif constructs in previous recipes of this chapter. CMake also offers language facilities for creating loops: foreach-endforeach and while-endwhile. Both can be combined with break for breaking from the enclosing loop early. This recipe will show you how to use foreach to loop over a list of source files. We will apply such a loop to lower the compiler optimization for a set of source files without introducing a new target.

Getting ready

...
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 : 9781788472340
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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
$279.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 $ 148.97
C++ Reactive Programming
$48.99
CMake Cookbook
$60.99
The Modern C++ Challenge
$38.99
Total $ 148.97 Stars icon
Banner background image

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

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.