Minimal CMake - Tom Hulton-Harrop - E-Book

Minimal CMake E-Book

Tom Hulton-Harrop

0,0
29,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Minimal CMake guides you through creating a CMake project one step at a time. The book utilizes the author's unique expertise in game and engine development to craft compelling examples of how CMake can be used to build complex software. The chapters introduce concepts gradually, each one building on the last. Throughout the course of the book, you will progress from a simple console application all the way through to a full windowed app.
The book will help you build a strong foundation in CMake that will translate to future projects. You'll learn how to integrate existing software libraries to enhance your app's functionality, how to build reusable libraries to share with others, and how to manage developing for multiple platforms simultaneously, including macOS, Windows, and Linux. You'll also find out how CMake facilitates testing and how to package your application ready for distribution.
The book aims to not overwhelm you with everything there is to know about CMake. Instead, it focuses on the most relevant and important parts that will help you become productive quickly.
By the end of this book, you will be a confident CMake user and will have gained the skills and experience to build and share your own libraries and applications.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 385

Veröffentlichungsjahr: 2025

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Minimal CMake

Learn the best bits of CMake to create and share your own libraries and applications

Tom Hulton-Harrop

Minimal CMake

Copyright © 2024 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Kunal Sawant

Publishing Product Manager: Samriddhi Muraka

Book Project Manager: Prajakta Naik

Technical Review Editor: Farheen Fathima

Senior Editor: Aditi Chatterjee

Technical Editor: Jubit Pincy

Copy Editor: Safis Editing

Proofreader: Aditi Chatterjee

Indexer: Rekha Nair

Production Designer: Jyoti Kadam

DevRel Marketing Coordinator: Shrinidhi Manoharan

First published: September 2024

Production reference: 1200924

Published by Packt Publishing Ltd.

Grosvenor House

11 St Paul’s Square

Birmingham

B3 1RB, UK

ISBN 978-1-83508-731-2

www.packtpub.com

This book would not have been possible without the love, support, and encouragement of my incredible wife, Fi. Thank you for your warmth, kindness, and patience throughout this whole experience. I’d also like to thank my amazing mum, Jane, and sister, Lizzie, for always being there for me. Thank you both for everything over the years; I wouldn’t be the person I am today without you.

– Tom Hulton-Harrop

I’d also like to take a moment to thank all the people who’ve contributed to this book over the course of many months. I owe a sincere debt of gratitude to Akash Sharma who contacted me in the first place about writing a book about CMake, without the push from you this never would have happened. I’d also like to thank the dedicated and talented members of the Packt publishing team who helped keep the book on track and improve it in many ways, in particular Aditi Chatterjee who was a phenomenal editor throughout. I’d also like to extend sincere thanks to my two technical reviews, Derric McGarrah and John Coimbra Walsh, both CMake experts in their own right, their feedback, questions and suggestions helped improve the book no end. Finally, I’d like to thank Omar Cornut for graciously allowing me to use the Dear ImGui Test Engine in several examples in the book (as well as authoring the spectacular Dear ImGui library itself).

– Tom Hulton-Harrop

Contributors

About the author

Tom Hulton-Harrop is a software developer with over 10 years of experience in game and engine development. Tom started his career in 2011 at Electronic Arts working on the Need for Speed series of racing games. In 2014, he joined Fireproof Games where he worked on The Room Three and a little-known VR game called Omega Agent. After a stint at a small start-up called Glowmade, Tom joined Amazon as part of the Lumberyard Game Engine team (later becoming Open 3D Engine). During this time, Tom became interested in open source development and started sharing multiple hobby projects on GitHub. It was this experience that led Tom to CMake, where he slowly came to appreciate the power and simplicity of the tool. Tom now works at a start-up called Amutri, helping deliver 3D experiences to engineering, manufacturing, and lighting customers.

About the reviewers

Derric McGarrah is a Senior Software Engineer with 15 years of experience across various fields, including enterprise document management software, video game and engine development, casino slot software, and network provisioning. He has experience designing and implementing build pipelines using CMake and is a major contributor to the O3DE CMake system. In his free time, Derric enjoys tinkering with C++, Bash, and Python to automate his home network, while staying up to date with the latest C++ standards.

Derric has built enterprise solutions for various companies (HP, AWS, etc.) and contributed to open-source projects, including the official CMake repository.

I would like to thank Tom for authoring this book and providing me with the opportunity to review it. I believe it can serve as a gateway for guiding more developers toward becoming experts in CMake.

Jonathan Coimbra Walsh is an avid programmer and musician currently residing in Orange County, California. Originally from the United Kingdom, he divides his time between exploring new countries and continents with his wife, Mayara, developing his own audio software projects, and enjoying the sun at the beach. Jonathan’s background is a blend of academia, where he taught game engine programming and audio software development, and industry, where he worked as a Senior Software Engineer for Amazon and Samsung in both game and mobile development.

Table of Contents

Prefacexiii

Part 1: Starting Up

1

Getting Started3

Technical requirements

Installing CMake on Windows

Installing CMake on macOS

Installing CMake on Linux (Ubuntu)

Installing Git

Visual Studio Code setup (optional)

Summary

2

Hello, CMake!21

Technical requirements

Using CMake from the command line

Linux/macOS

Windows

Exploring the repository

Invoking CMake

Building with CMake

Examining our first CMakeLists.txt file

Setting a minimum version

Naming the project

Declaring the application

Adding source files

CMake generators

Specifying a generator

CMake configs

Project next steps

Adding another file

Adding a dynamic array

Forgetting to add a file

To GLOB or not to GLOB

Referencing interface files in target_sources

Summary

3

Using FetchContent with External Dependencies39

Technical requirements

Why FetchContent

When to use FetchContent

When not to use FetchContent

Using FetchContent

Including other CMake code

Describing our dependency

Using libraries from GitHub

Using branch names

Using local libraries with FetchContent

Making the dependency available

Linking to the dependencies

Setting options on dependencies

Updating our application

Summary

4

Creating Libraries for FetchContent55

Technical requirements

Making a library compatible with FetchContent

Project structure

The CMakeLists.txt file

Creating the library

Generator expressions

Include interfaces

Using our library

Moving Game of Life to a library

Making Game of Life a shared library

Making things work on Windows

Making things relocatable on macOS and Linux

Final cross-platform additions

Interface libraries

Summary

Part 2: Scaling Up

5

Streamlining CMake Configuration79

Technical requirements

Reviewing how we use CMake

Using scripts to avoid repetitive commands

Moving to CMake presets

Going further with CMake presets

CMake preset overrides

Other kinds of CMake presets

A return to the CMake GUI

Summary

6

Installing Dependencies and ExternalProject_Add97

Technical requirements

What is installing?

Installing a library

Using an installed library

CMake search modes

Returning to find_package

Informing CMake where to find our library

Providing the location of our library

CMakePreset improvements

Using ExternalProject_Add to streamline installation

Improving our use of ExternalProject_Add

Handling multiple libraries with ExternalProject_Add

Running the bgfx example

Summary

7

Adding Install Support for Your Libraries119

Technical requirements

Adding install support to a library

The CMake install command

Using our newly installed library

Dealing with nested dependencies

Private nested dependencies

Public nested dependencies

When and how to add COMPONENTS

Supporting different versions of a library

Writing a find module file

Summary

8

Using Super Builds to Simplify Onboarding141

Technical requirements

Using ExternalProject_Add with your own libraries

Configuring a super build

Integrating super build support

Automating scripts with CMake

Invoking the CMake script from CMakeLists.txt

Setting options in nested files

Installing an application

Summary

Part 3: Wrapping Up

9

Writing Tests for the Project167

Technical requirements

Understanding CTest

Adding unit tests to a library

CMakeLists.txt changes for CTest

Running the tests

Adding end-to-end tests to an application

Integrating a UI library

Integrating end-to-end tests using Dear ImGui

Integrating end-to-end tests with CTest

Adding other kinds of tests

Internal tests

CMake script tests

Using CDash with CTest

Creating a CDash project

Uploading test results

Adding code coverage

Summary

10

Packaging the Project for Sharing189

Technical requirements

Understanding CPack

Loading resources relative to the executable

Integrating CPack

CPack common properties

The CPack Windows NSIS package

The CPack macOS bundle package

The CPack Linux Debian package

Building a macOS bundle

Adding CPack presets

Other uses for CPack

Summary

11

Supporting Tools and Next Steps211

Technical requirements

CMake Tools for Visual Studio Code

Navigating the Minimal CMake source code

Configuring, building, and debugging

Visual Studio Code and CMake presets

Debugging CMakeLists.txt files

Visual Studio Code extras

Syntax highlighting

Generating compile_commands.json

Code auto-formatting

Diff Folders

CMake with other IDEs

Visual Studio

Xcode

CLion

C/C++ build recommendations

Unity builds

CMake script structure

Future topics

Summary

Index235

Other Books You May Enjoy242

Preface

We are thrilled you’ve decided to pick up Minimal CMake to either get introduced to CMake or to expand your knowledge of what is possible with it today. If you are interested in learning about how CMake can help you create libraries and applications, integrate with world-class open source software, or how it can be used to share your creations with others, you’re in the right place.

The title of this book is a little tongue-in-cheek, but the idea is to get to the good bits of CMake as fast as possible, skipping over some areas and avoiding others entirely. CMake is at its best when it does what you need it to do, and then gets out of your way. You don’t need to be a CMake expert to wield it effectively, and whether you’re new to CMake or have been away a while and are returning to see what’s changed, this book will have something for you.

An important aspect of this book is its focus on practical examples. It will take you step by step from a simple console application, all the way through to a full windowed app that runs on macOS, Windows, and Linux. Each chapter builds on the last, and every chapter is accompanied by source code split into multiple parts, each incrementally building on what came before. You will witness step by step how the journey unfolds and the reasoning and trade-offs behind every change.

In Part 1, we’ll make sure everyone has the tools they need to get CMake set up on their system of choice. We’ll then walk through some simple CMake scripts to get familiar with the most fundamental CMake commands. Next, we’ll turn our attention to a relatively new and incredibly powerful addition to CMake that makes integrating external libraries trivial. As well as showing how to integrate external code, we’ll show you how to make your own code sharable by creating a reusable library ourselves.

Part 2 builds on the foundations laid by Part 1. We’ll start by introducing some incredibly useful quality-of-life improvements that have been added to CMake in recent years. These eliminate a lot of tedious commands while keeping our CMake scripts clean and simple. We’ll also start to introduce larger dependencies and understand strategies for how to handle them, as well as how to create them ourselves. We’ll wrap things up by showing how to create a unified build that can configure and build our application, libraries, and dependencies all with a single command.

In Part 3, we’ll cover some other important areas where CMake can help us build and share better software. We’ll see how to add many kinds of tests to both our libraries and applications, as well as how to tie them together with the help of the companion tool, CTest. We’ll also gain an appreciation for how CMake can help us package our application, so it runs not just on our machine, but anywhere. We’ll wrap things up by reviewing what other great tools are available that can make working with CMake easier, and where to go next to continue building your CMake knowledge.

Why CMake?

CMake is one of those tools that unfortunately (though, not necessarily undeservedly) has a bit of a bad reputation. There are many developers out there who’ve been burned by CMake. They may have been forced to interact with it in a legacy code base, having had to deal with significant complexity, reams of CMake scripts, and questionable practices. Alternatively, they may have tried to use it for a new project, only to get stuck and frustrated trying to get things to work. As CMake has been around for a long time, there are many outdated examples and resources referencing old versions of CMake without all the latest features (and the benefit of hindsight about what works, and what not to do). As with any successful framework or language, CMake also comes with a certain amount of baggage, which is unfortunately unavoidable.

With all that being said, the good news is that over the last few years, there has been somewhat of a renaissance in CMake, and from version 3.0 (technically 2.8 for the diehards) onward, the new functionality to compose complex projects from targets has made an enormous difference, and it has been slowly gaining in popularity since.

One of the reasons for CMake’s growing popularity is a crucial detail that cannot be overstated. If you describe your build using CMake, you’ll by default have a project that you can build on Windows, Linux, and macOS. If you instead start a project with Visual Studio on Windows, Xcode on macOS, or Make files on Linux, it’s harder to migrate to other platforms, and harder for others working on different platforms to contribute. Having your build settings and options stored in versioned, human-readable scripts is incredibly useful (no more searching through nested tabs and windows in IDEs to find the right value to change).

The other interesting development is with this increasing popularity, CMake is now the lingua franca of build systems in C and C++. If a C or C++ project lives on GitHub, chances are it’s using CMake, and even if it’s not, with a minimal amount of effort, it’s possible to write a simple integration or wrapper to make that library consumable from CMake. This unlocks a vast wealth of potential, as adding a dependency to provide improvements to your project suddenly becomes a few lines of code, instead of an agonizing, laborious, and time-consuming process, usually requiring either embedding code from other libraries in your project or downloading and writing the code to build those libraries yourself.

Using CMake to build your projects and knowing enough CMake to get by (you most certainly do not need to be an expert) will make writing your applications faster, more maintainable, and more collaborative. It will also make working with C or C++ more fun (we promise), and not only C and C++, as there’s CMake support for C#, Fortran, CUDA, Objective-C, and Swift at the time of publication.

CMake is by no means perfect, but today, it is ubiquitous across the C and C++ landscape, and it is constantly evolving and improving thanks to the excellent work of the developers at Kitware and the many impactful open source contributors. We’re convinced, that whether you’re a professional C++ developer with years of experience, or a student or hobbyist just starting out, picking up, or getting reacquainted with CMake, will make you a happier, more productive developer. The experience you’ll gain when it comes to things such as dependency management and project structure will also serve you well in the future.

Let’s now turn our attention toward which group you feel most aligned with to help get the most out of this book.

Who this book is for

We appreciate that there is a broad spectrum of people who may be interested in reading this book, and so we’d like to provide some specific details for each type of reader to help better prepare you for the material.

Students

If you are a computer science or software engineering student, then this book may be of interest to you to help introduce you not only to CMake, but also to cross-platform development, static versus shared libraries, code structure, and testing. The information within will provide a solid foundation for making your own desktop applications, be they games, tools, or simulations. Some topics may be unfamiliar, but by studying the code and following the recommended links, you’ll quickly pick up the content.

Experienced C/C++ developers

If you’re coming to this book with a lot of existing experience building C/C++ libraries and/or applications, a lot of the fundamental topics may be familiar, but the ways in which you can use CMake to configure and set things up efficiently will be of interest (e.g., topics relating to dynamic library loading and RPATH handling for example). The example project also makes use of some interesting libraries (in particular, the graphics library, bgfx, and user interface library, Dear ImGui), which may be of interest, as well as their handling in CMake. How CMake handles installing and packaging is likely to also be relevant (particularly how to correctly configure installers/disk images correctly using CMake).

Experienced developers (other languages)

If you’re an experienced developer familiar with other languages (such as JavaScript/TypeScript, Java, C#, Python, Rust) then you’ll be certain to be able to follow the content with ease. Hopefully, the parallels between CMake and the build system you use in your existing language/framework should make picking up the concepts simpler (especially when it comes to dependency management). The examples should also act as a refresher for C/C++ if you’re new to (or estranged from) the language.

Hobbyists

If you’re a hobbyist developer looking to build your first game or tool to share with friends, family, or coworkers, then this book should give you everything you need to get started. If you want to build a windowed application or stick with something that can be run from the terminal, we’ve got you covered. The information showing how to integrate third-party libraries should be particularly useful in helping you become as productive as possible in a short space of time.

What this book covers

Chapter 1, Getting Started, covers everything you’ll need to get up and running with CMake whether you’re on Windows, macOS, or Linux.

Chapter 2, Hello, CMake!, takes you on a whistle-stop tour of CMake, introducing some of the most fundamental concepts and the heart of the application we’ll be building over the course of the book.

Chapter 3, Using FetchContent with External Dependencies, shows you how to bring in our first external dependency to enhance our application with minimal effort.

Chapter 4, Creating Libraries for FetchContent, swaps things around, and shows you how to create a library that can then be consumed by FetchContent.

Chapter 5, Streamlining CMake Configuration, switches gears to focus on how to set up CMake to work as efficiently as possible and eliminate verbose commands.

Chapter 6, Installing Dependencies and ExternalProject_Add, builds on Chapter 5 and shows you how best to handle larger dependencies in your project.

Chapter 7, Adding Install Support for Your Libraries, walks through how to make your library installable so it can be used in the same way as the dependencies we explored in Chapter 6.

Chapter 8, Using Super Builds to Simplify Onboarding, is a return to streamlining the project, with a demonstration of how to build your project and multiple external dependencies with one command.

Chapter 9, Writing Tests for the Project, explores the importance of testing and outlines where CTest can help consolidate many kinds of tests.

Chapter 10, Packaging the Project for Sharing, covers the final piece of the puzzle when it comes to getting your project ready to share with others.

Chapter 11, Supporting Tools and Next Steps, looks at the wider CMake ecosystem and describes a host of tools that complement CMake itself, as well as sharing ideas about topics and resources that will help you learn more about CMake in the future.

To get the most out of this book

Following along will be a bit easier if you have some limited experience in the following:

Basic knowledge of C/C++ (or a similar procedural language such as Java or C#)Familiarity with the terminal/command lineExperience working with a code editor (e.g., Visual Studio Code)Awareness of basic graphics programming concepts (a bonus; this is to understand some of the later examples, but is not required)

We hope this book gives you an understanding and appreciation for what CMake can do to make building applications easier. It will give you a strong foundation on which to build and structure new projects that will make using other’s code, as well as sharing your own, straightforward.

Software/hardware covered in the book

Operating system requirements

C, C++, CMake, CTest, CPack, Visual Studio Code

Windows, macOS, Linux

We recommend you clone the accompanying repository that comes with this book to read through the code and run the examples to gain a deeper understanding of how things work. We also recommend using a text comparison tool (a diff tool) to compare chapter parts as the libraries and applications evolve over time.

Download the example code files

You can download the example code files for this book from https://github.com/PacktPublishing/Minimal-CMake. If there’s an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “We’ll cover the changes we need to make to our CMakeLists.txt file and the commands needed to create the package.”

A block of code is set as follows:

cmake_minimum_required(VERSION 3.28) project(mc-array LANGUAGES C)

Any command-line input or output is written as follows:

Shaders not found. Have you built them using compile-shader-<platform>.sh/bat script?

Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “Once this is completed, close and open Terminal and return to Developer Command Prompt for VS 2022.”

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts

Once you’ve read Minimal Cmake, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below

https://packt.link/free-ebook/9781835087312

Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly

Part 1: Starting Up

The first part of this book begins by ensuring you have everything you need to get started with CMake, whether you’re on Windows, macOS, or Linux. Once your environment is up and running, we’ll introduce CMake itself, starting with the foundations of our project, which will evolve throughout the course of this book. With our simple application operational, we’ll turn our attention to how to use other people’s code with the help of CMake by showing how easy it can be to bring in third-party dependencies in a clean and succinct way. Before moving on to Part 2 of the book, we’ll show how to extract part of our application into a reusable library that itself can be shared with others and used by our main application.

This part has the following chapters:

Chapter 1, Getting StartedChapter 2, Hello, CMake!Chapter 3, Using FetchContent with External DependenciesChapter 4, Creating Libraries for FetchContent

1

Getting Started

The objective of Minimal CMake is to walk you through the development process of taking an application from its humble beginnings (starting with a simple console application) to a complete windowed application you can demo to friends and use as a template for future projects.

We’ll see how CMake can help throughout the entire process. Perhaps the greatest benefit CMake provides is how easy it is to integrate existing open source software to improve the functionality of your app.

Before we can start using CMake to create our application, we need to ensure that we have our development environment set up and ready to go. The setup will vary depending on which platform you’ve decided to use (Windows, macOS, or Linux). We’ll cover each system here. This will provide a good starting point to build on as we introduce CMake and begin assembling the core of our application.

In this chapter, we’re going to cover the following topics:

Installing CMake on WindowsInstalling CMake on macOSInstalling CMake on Linux (Ubuntu)Installing GitVisual Studio Code setup (optional)

Technical requirements

To get the most out of this book, we recommend that you run the examples locally. To do this you will need the following:

A Windows, Mac, or Linux machine with an up-to-date operating system (OS)A working C/C++ compiler (a system default is recommended for each platform if you don’t already have this)

The code examples in this chapter can be found by following this link: https://github.com/PacktPublishing/Minimal-CMake.

CMake version

All examples in this book have been tested with CMake 3.28.1. Earlier versions are not guaranteed to work. Later versions should be safe to upgrade to, though it’s possible that there may be differences. If in doubt, use CMake 3.28.1 when running the examples from this book.

Installing CMake on Windows

In this section, we’ll cover how to install everything you’ll need to start building applications with CMake on Windows.

To begin with, you will need a C/C++ compiler. If you don’t already have a compiler installed, a good choice to go with is Visual Studio (Visual Studio 2022 Community Edition can be downloaded from https://visualstudio.microsoft.com/vs/community/).

Visual Studio is an integrated development environment that comes with Microsoft’s C++ compiler for Windows (cl.exe). We won’t be covering Visual Studio directly, though you are more than welcome to use it if you prefer (see Chapter 11, Supporting Tools and Next Steps for a brief summary). We’ll cover how to generate Visual Studio solution files and invoke MSBuild to build our project. To keep things as consistent as possible, we’ll use Visual Studio Code for most of the examples. This is more for convenience than anything else, and if you’re more comfortable with another tool, by all means use it. As CMake has grown in popularity, Visual Studio has expanded support for CMake considerably, which is worth investigating if you’re predominantly going to be developing on Windows.

Visual Studio versus Visual Studio Code

Although they sound similar, Visual Studio and Visual Studio Code are two hugely different applications. Visual Studio is an integrated development environment from Microsoft that runs predominantly on Windows (there is also, confusingly, a version of Visual Studio for macOS which is quite different to the Windows application). Visual Studio is used for building Windows applications in C++ or .NET (C#, F#, and Visual Basic). Visual Studio Code on the other hand is a cross-platform code editor that runs on Windows, macOS, and Linux. It has an extensive extension library that allows it to be used with many different programming languages. It’s popular for web development, having excellent support for TypeScript and JavaScript, though it also has robust support for C++ through the C/C++ extension from Microsoft. Visual Studio Code is what we’ll use throughout this book.

Open the Visual Studio installer and select Visual Studio Community 2022 (if there’s a later version available when you’re reading this, feel free to grab that instead).

Figure 1.1: Visual Studio Installer version selector

After selecting Visual Studio Community 2022, a new panel will appear. The Workloads tab lets you select an option to include a set of sensible defaults. Scroll down and select Desktop development with C++.

Figure 1.2: Visual Studio Installer workload selector

There are several optional components selected by default on the right. It won’t hurt to leave them selected. You can remove certain features such as Image and 3D model editors and Test Adapter for Boost/Google.Test if you prefer.

After confirming your selection, click on Install in the bottom-right corner of the window.

Once the installation is complete, go to the Windows Start menu and follow these steps:

Figure 1.3: Windows 11 Taskbar Search Box

Search for Terminal.

Figure 1.4: Windows 11 application search results

Open the Terminal app. Then, from the top bar, click the dropdown and select Developer Command Prompt for VS 2022.

Figure 1.5: Microsoft Terminal new tab selector

Customizing Command Prompt

It is possible to modify the default Command Prompt in Windows Terminal to run VsDevCmd.bat when it’s launched with the host and target architectures specified. To do this, go to Settings from the Windows Terminal drop-down menu and then select Open JSON file in the lower-left corner of the screen. In the profiles section, find the Command Prompt entry under list and change the commandLine property to include the path to VsDevCmd.bat and the required architectures (e.g., "commandline": "%SystemRoot%\\System32\\cmd.exe /k \"C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\Common7\\Tools\\VsDevCmd.bat\" -arch=x64 -host_arch=x64"). It’s also possible to call VsDevCmd.bat when opening Git Bash from Windows Terminal (see the Installing Git section if you don’t already have it installed). To do this, find Git Bash in the list of profiles and add the following: "commandLine": "\"C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\Common7\\Tools\\VsDevCmd.bat\" -arch=x64 -host_arch=x64 && \"%PROGRAMFILES%/Git/bin/bash.exe\" -i -l"

To verify that the Microsoft compiler is working as expected, run cl.exe. You should then see the following printed (the architecture will vary depending on the machine you’re using):

Figure 1.6: Running cl.exe from Developer Command Prompt

CMake and Visual Studio

Visual Studio comes bundled with its own version of CMake, which you can rely on and skip the following two steps. It is located in C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin. Running cmake --version will show cmake version <version>-msvc1, which indicates that the version is distinct from normal CMake.

If you do not currently have CMake installed on your system (or have a fairly old version of CMake installed), head to https://cmake.org/download/ to get the latest release (at the time of writing, this is 3.28.1).

The simplest option is to grab the Windows x64 installer (cmake-3.28.1-windows-x86_64.msi) and follow the standard installation instructions.

Figure 1.7: CMake Windows installer

Ensure that you select Add CMake to the system PATH for the current user.

Figure 1.8: CMake installer PATH options

Follow the remaining installation instructions and wait for CMake to install. Once this is completed, close and open Terminal and return to Developer Command Prompt for VS 2022.

Run cmake and cmake --version and you should see the following:

Figure 1.9: Running cmake.exe from Developer Command Prompt

And with that, we’re ready to start building with CMake.

Installing CMake on macOS

In this section, we’ll cover how to install everything you’ll need to start building the application on macOS.

To begin, you will need a C/C++ compiler. If you don’t already have a compiler installed, the safest bet is to go with Xcode, which can be downloaded from the App Store:

Go to Spotlight Search by clicking the magnifying glass on the macOS menu bar.

Figure 1.10: Spotlight Search option on macOS menu bar

Search for App Store.

Figure 1.11: Searching for App Store from Spotlight Search

From App Store, searchfor Xcode.

Figure 1.12: Xcode search results from the App Store

Click the Get and then Install buttons.

Figure 1.13: Xcode application install

It is also possible to install Command Line Tools for Xcode from https://developer.apple.com, specifically https://developer.apple.com/download/all/, which also includes the core tools we’ll need to work with CMake. To access the Apple Developer website, an Apple Developer account is needed (you can learn more here: https://developer.apple.com/account).

Once either Xcode or Command Line Tools for Xcode have been installed, open the macOS Terminal app (by going to Spotlight Search and typing Terminal again) and enter the following: % clang --version

You should see a message resembling the following:

Apple clang version 15.0.0 (clang-1500.3.9.4) ...

This confirms that we have a working compiler and can now install CMake to work with it.

If you do not currently have CMake installed on your system (or have a fairly old version of CMake installed), head to https://cmake.org/download/ to get the latest release (at the time of writing this is 3.28.1).

The simplest option is to grab the macOS 10.13 or later disk image (.dmg) (cmake-3.28.1-macos-universal.dmg) and follow the standard installation instructions.

Figure 1.14: CMake macOS installation

Drag CMake to your Applications folder.

The CMake GUI will now be available on your system but CMake won’t yet be available from Terminal.

To be able to run CMake commands from Terminal, open CMake from the Applications folder, ignore the UI that appears for now, and go to the CMake macOS menu bar and click Tools| How to install For Command Line Use.

Figure 1.15: CMake command-line install options from macOS menu bar

After clicking this, a popup will appear with several options. The least invasive is likely the first option, though the second is also a fine choice.

Figure 1.16: CMake command-line install options panel

To have the path option persist, we need to update our .zshrc file. Copy the following line: PATH="/Applications/CMake.app/Contents/bin":"$PATH"From Terminal, ensure you are in the home directory (cd ~) and then open your .zshrc file (feel free to do this in your favorite text editor or type nano .zshrcfrom Terminal).

Figure 1.17: Opening .zshrc with nano from Terminal

Paste the earlier command and save the file.

Figure 1.18: Modifying .zshrc from nano inside Terminal

To reload the Zsh config file and update the PATH variable, run source .zshrc.

Figure 1.19: Refresh the Terminal environment by executing .zshrc again

Finally, run cmake from Terminal to verify that it can be found.

Figure 1.20: Running cmake from Terminal

You can also use where cmake and cmake --version to verify that you have the correct version installed.

With that, we’re ready to start building with CMake.

Installing CMake on Linux (Ubuntu)

In this section, we’ll cover how to get everything you’ll need to start building the application on Linux (Ubuntu).

To begin with, you will need a C/C++ compiler. If you don’t already have a compiler installed, an excellent choice is to go with GCC. This can be installed by using the standard Ubuntu package manager, apt:

Open Terminal by using Show Applications from the desktop.

Figure 1.21: Ubuntu Show Applications menu option

Run sudo apt update and then sudo apt install build-essential (it is possible that your version of Ubuntu already comes with this installed, but it’s good to check).

Figure 1.22: Installing build-essential from Terminal

Run gcc --version to verify that the compiler can be found and is working as expected. You should see output resembling the following: gcc (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0 ...

Figure 1.23: Running gcc --version from Terminal

Next, we need to install CMake. This can be done via a package manager (e.g., apt), but we’ll do so directly here to specify the precise version. Go to https://cmake.org/download/ and scroll down to find the binary distributions section. Grab Linux x86_64 (Intel) (cmake-3.28.1-linux-x86_64.tar.gz) or Linux aarch64 (ARM) (cmake-3.28.1-linux-aarch64.tar.gz) depending on your architecture.Run this command from the folder you downloaded CMake to extract and install CMake to your /opt folder: sudo tar -C /opt -xzf cmake-3.28.1-linux-aarch64.tar.gz

(It’s perfectly reasonable to extract the files to a local folder and update your PATH variable to point to the bin folder. Installing to /opt is one common approach).

You can alternatively just double-click the tar.gz file and use the Archive Manager Extract option:Click the Extract option and then go to Other Locations | Computer and select the opt folder.Then click Extract again in the top-right corner.

Figure 1.24: Ubuntu Archive Manager Extract dialog

Go to your home directory (cd ~) and enter nano .bashrc.

Figure 1.25: Opening .bashrc with nano from Terminal

Add the bin subfolder in the directory you extracted in your /opt folder to your PATH variable with the following line:PATH="/opt/cmake-3.28.1-linux-aarch64/bin":"$PATH"

(The architecture may differ in your specific case, such as by having cmake-3.28.1-linux-x86_64 instead of cmake-3.28.1-linux-aarch64).

Figure 1.26: Modifying .bashrc from nano inside Terminal

With that, save the file and close nano (Ctrl+O, Ctrl+X). Then run source .bashrc to reload the .bashrc file and update the PATH variable in the current Terminal session.Finally, type cmake and hit return to confirm that things are working as expected. You should see the following printed:

Figure 1.27: Running cmake from Terminal

As a last step, run sudo apt-get install libgles2-mesa-dev to ensure you have the dependencies needed to run some of the later examples in the book.

With that, we’re ready to start building with CMake.

Installing Git

To follow the examples provided in each chapter and retrieve the accompanying source code for this book (available from the book’s website https://github.com/PacktPublishing/Minimal-CMake), it is recommended to have Git installed on your system.

The easiest way to do this is to go to https://git-scm.com/downloads and download Git for your chosen platform if you do not already have it installed.

On macOS, Git is installed as part of the Xcode installation we walked through in Installing CMake on macOS. On Windows, download the 64-bit installer and run the installation. On Linux (Ubuntu), run sudo apt-get install git from the terminal.

Type git from the command line to verify that the tool is available.

Visual Studio Code setup (optional)

To ensure a consistent experience throughout the book, Visual Studio Code will be used along with the native terminal to walk through code examples, be that on Windows, macOS, or Linux. The following section outlines how to get set up with Visual Studio Code and configure your development environment. If you would prefer to use a different editor, that’s fine. All that is needed to follow along is a C/C++ compiler and CMake. Visual Studio Code is simply used as a cross-platform editor (it also comes with some excellent CMake support that is covered in Chapter 11, Supporting Tools and Next Steps).

To install Visual Studio Code, go to https://code.visualstudio.com/Download. There are links for Windows, Linux, and macOS there. Follow the installation instructions for your platform of choice. On Windows, choose User Installer and follow the setup instructions.

On Linux, either download the .deb package and use the Software Install application or download the code-stable-...tar.gz file and extract it to /opt similarly to how we extracted CMake (e.g., sudo tar -C /opt -xzf code-stable-arm64-1702460949.tar.gz). After extracting it, add /opt/VSCode-linux-<arch>/bin to your path by updating your .bashrcfile again.

On Mac, download the .zip file, extract it, and then drag and drop the Visual Studio Code application into your Applications folder (this can be done from Finder).

One point to mention is that it’s helpful to ensure that Visual Studio Code is added to your PATH so it can be opened easily from the command line (usingcode . from your project or workspace folder). This can be done as part of the installation wizard on Windows or by updating .bashrc on Linux. On macOS, there is a way to do this from within Visual Studio Code. Open Visual Studio Code and press either F1, Shift + Cmd +P (macOS) or press Shift + Ctrl + P for Windows or Linux. Alternatively, from the menu bar, you can click View | Command Palette. Once the command palette is open, type shell. The action “Shell Command: Install ‘code’ command in PATH” will display. A popup will appear prompting osascript to make changes to the system. Confirm this by entering your user password and then open an instance of Terminal to verify that Visual Studio Code can be started by running code.

Once Visual Studio Code is installed and up and running, navigate to the Extensions option on the left panel and search for C/C++ extension pack.

Figure 1.28: Extensions view in Visual Studio Code

The C/C++ Extension Pack extension comes with the C/C++ extension, which supplies IntelliSense and debugging features. The extension pack also includes CMake language support and CMake Tools, a CMake integration for Visual Studio Code.

Now that we have Visual Studio Code installed, we can guarantee a consistent experience when developing across all platforms. Using Visual Studio Code is completely optional, but it is highly recommended. In Chapter 11, Supporting Tools and Next Steps, we’ll show you how CMake and Visual Studio Code complement one another.

Summary

In this chapter, we walked through everything you need to begin development with CMake. We installed a C/C++ compiler on Windows, macOS, and Linux and installed CMake on each platform. We saw how to install Git and walked through how to install Visual Studio Code and enable several useful extensions. Having our environment configured correctly is important to ensure that the later examples we’ll work through behave as expected. We now have everything we need to start using CMake and can start developing our project to understand how CMake can accelerate how we build software.

In the next chapter, we will introduce CMake and look at the commands you will commonly run from the terminal. We’ll also look at some of the core commands that make up a CMake script. We’ll get a basic application up and running and learn about generators, build types, and more.

2

Hello, CMake!

We’re now going to start using CMake. We’ll first introduce the commands we run frequently from the terminal and then those we write in our CMake scripts. We’ll do this by starting with a Hello, CMake! application (a throwback to everyone’s favorite Hello, World! program) bootstrapped with a minimal CMake script, examining each CMake command we use in depth. These commands will soon become second nature and make building your code effortless.

CMake has a rich feature set, but luckily there’s a pretty small amount to learn to start becoming productive. There are lots of options to handle complex use cases; most of which we fortunately don’t need to worry about for the moment. It’s good to know they’re there, but don’t feel you need to learn all there is to know about the commands or CMake language at the outset. There’s plenty of time for that as your project matures.

In this chapter, we’re going to cover the following topics:

Using CMake from the command lineExamining our first CMakeLists.txt fileCMake generatorsProject next stepsAdding another file

Technical requirements

To follow along, please ensure you have met the requirements outlined in Chapter 1, Getting Started. These include the following:

A Windows, Mac, or Linux machine with an up-to-date operating system (OS)A working C/C++ compiler (a system default is recommended for each platform if you don’t already have this)

The code examples in this chapter can be found by following this link: https://github.com/PacktPublishing/Minimal-CMake.

Using CMake from the command line

Before delving into the contents of our first CMake script, let’s clone the repository holding the code examples from the book. This can be performed by opening a terminal session and running the following commands.

Linux/macOS

Run these commands if you’re working on Linux/macOS:

cd ~ # User's home directory on Linux/macOS (feel free to pick another location) mkdir minimal-cmake cd minimal-cmake git clone https://github.com/PacktPublishing/Minimal-CMake.git .

You’re now set up to explore the book repository on macOS or Linux.

Windows

Run these commands is you’re workingon Windows: