Book Image

CMake Best Practices

By : Dominik Berner, Mustafa Kemal Gilor
5 (2)
Book Image

CMake Best Practices

5 (2)
By: Dominik Berner, Mustafa Kemal Gilor

Overview of this book

CMake is a powerful tool used to perform a wide variety of tasks, so finding a good starting point for learning CMake is difficult. This book cuts to the core and covers the most common tasks that can be accomplished with CMake without taking an academic approach. While the CMake documentation is comprehensive, it is often hard to find good examples of how things fit together, especially since there are lots of dirty hacks and obsolete solutions available on the internet. This book focuses on helping you to tie things together and create clean and maintainable projects with CMake. You'll not only get to grips with the basics but also work through real-world examples of structuring large and complex maintainable projects and creating builds that run in any programming environment. You'll understand the steps to integrate and automate various tools for improving the overall software quality, such as testing frameworks, fuzzers, and automatic generation of documentation. And since writing code is only half of the work, the book also guides you in creating installers and packaging and distributing your software. All this is tailored to modern development workflows that make heavy use of CI/CD infrastructure. By the end of this CMake book, you'll be able to set up and maintain complex software projects using CMake in the best way possible.
Table of Contents (22 chapters)
Part 1: The Basics
Part 2: Practical CMake – Getting Your Hands Dirty with CMake
Part 3: Mastering the Details

Fundamental building blocks of modules – functions and macros

It is clear that we need some basic building blocks to create utility modules. The most fundamental building blocks for utility modules are functions and macros, so it is essential to learn their working principles well. Let's start by learning about functions.


Let's remember what we have learned in Chapter 1, Kickstarting CMake, about functions. A function is the CMake language feature to define a logical code block that can be invoked to execute CMake commands. A function starts with function(…), has a body that contains CMake commands, and ends with the endfunction() CMake command. The function() command needs a name as the first argument, and optional function argument names, shown as follows:

function(<name> [<arg1> ...])

A function defines a new variable scope, so the changes made on CMake variables are only visible...