Modern CMake for C++
eBook - ePub

Modern CMake for C++

Rafal Swidzinski

Compartir libro
  1. 460 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Modern CMake for C++

Rafal Swidzinski

Detalles del libro
Vista previa del libro
Índice
Citas

Información del libro

Write comprehensive, professional-standard CMake projects and ensure the quality and simplicity of your solutionsPurchase of the print or Kindle book includes a free eBook in the PDF formatKey Features• Understand and automate compilation and linking with CMake• Manage internal and external dependencies easily• Add quality checks and tests as an inherent step for your buildsBook DescriptionCreating top-notch software is an extremely difficult undertaking. Developers researching the subject have difficulty determining which advice is up to date and which approaches have already been replaced by easier, better practices. At the same time, most online resources offer limited explanation, while also lacking the proper context and structure. This book offers a simpler, more comprehensive, experience as it treats the subject of building C++ solutions holistically. Modern CMake for C++ is an end-to-end guide to the automatization of complex tasks, including building, testing, and packaging. You'll not only learn how to use the CMake language in CMake projects, but also discover what makes them maintainable, elegant, and clean. The book also focuses on the structure of source directories, building targets, and packages. As you progress, you'll learn how to compile and link executables and libraries, how those processes work, and how to optimize builds in CMake for the best results. You'll understand how to use external dependencies in your project – third-party libraries, testing frameworks, program analysis tools, and documentation generators. Finally, you'll get to grips with exporting, installing, and packaging for internal and external purposes. By the end of this book, you'll be able to use CMake confidently on a professional level.What you will learn• Understand best practices for building C++ code• Gain practical knowledge of the CMake language by focusing on the most useful aspects• Use cutting-edge tooling to guarantee code quality with the help of tests and static and dynamic analysis• Discover how to manage, discover, download, and link dependencies with CMake• Build solutions that can be reused and maintained in the long term• Understand how to optimize build artifacts and the build process itselfWho this book is forThe book is for build engineers and software developers with knowledge of C/C++ programming who are looking to learn CMake to automate the process of building small and large software solutions. If you are someone who's just getting started with CMake, a long-time GNU Make user, or simply looking to brush up on the latest best practices, this book is for you.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Modern CMake for C++ un PDF/ePUB en línea?
Sí, puedes acceder a Modern CMake for C++ de Rafal Swidzinski en formato PDF o ePUB, así como a otros libros populares de Informatica y Sviluppo software. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
2022
ISBN
9781801071659
Edición
1
Categoría
Informatica

Section 1: Introducing CMake

Getting the basics right is critical to understanding the more advanced subjects and avoiding silly mistakes. This is where the majority of CMake users get in trouble: without a proper foundation, it's difficult to achieve the right outcome. No wonder. It's tempting to skip the introductory material and jump right in where the action is and get things done quickly. We address both points in this section by explaining the core topics of CMake and by hacking together a few lines of code to show what the simplest project looks like.
To build an appropriate mental context, we'll explain what CMake is exactly and how it does its job, along with what the command line is like. We'll talk about the different build stages and learn the language used to generate build systems. We'll also discuss CMake projects: what files they contain, how to approach their directory structure, and we'll explore their primary configuration.
This section comprises the following chapters:
  • Chapter 1, First Steps with CMake
  • Chapter 2, The CMake Language
  • Chapter 3, Setting Up Your First CMake Project

Chapter 1: First Steps with CMake

There is something magical about turning source code into a working application. It is not only the effect itself, that is, a working mechanism that we devise and bring to life, but the very process or act of exercising the idea into existence.
As programmers, we work in the following loop: design, code, and test. We invent changes, we phrase them in a language that the compiler understands, and we check whether they work as intended. To create a proper, high-quality application from our source code, we need to meticulously execute repetitive, error-prone tasks: invoking the correct commands, checking the syntax, linking binary files, running tests, reporting issues, and more.
It takes great effort to remember each step every single time. Instead, we want to stay focused on the actual coding and delegate everything else to automated tooling. Ideally, this process would start with a single button, right after we have changed our code. It would be smart, fast, extensible, and work in the same way across different OSs and environments. It would be supported by multiple Integrated Development Environments (IDEs) but also by Continuous Integration (CI) pipelines that test our software after a change is submitted to a shared repository.
CMake is the answer to many such needs; however, it requires a bit of work to configure and use correctly. This is not because CMake is unnecessarily complex but because the subject that we're dealing with here is. Don't worry. We'll undergo this whole learning process very methodically; before you know it, you will have become a building guru.
I know you're eager to rush off to start writing your own CMake projects, and I applaud your attitude. Since your projects will be primarily for users (yourself included), it's important for you to understand that perspective as well.
So, let's start with just that: becoming a CMake power user. We'll go through a few basics: what this tool is, how it works in principle, and how to install it. Then, we'll do a deep dive on the command line and modes of operation. Finally, we'll wrap up with the purposes of different files in a project, and we'll explain how to use CMake without creating a project at all.
In this chapter, we're going to cover the following main topics:
  • Understanding the basics
  • Installing CMake on different platforms
  • Mastering the command line
  • Navigating the project files
  • Discovering scripts and modules

Technical requirements

You can find the code files that are present in this chapter on GitHub at https://github.com/PacktPublishing/Modern-CMake-for-Cpp/tree/main/examples/chapter01.
To build examples provided in this book always use recommended commands:
cmake -B <build tree> -S <source tree>
cmake --build <build tree>
Be sure to replace placeholders <build tree> and <source tree> with appropriate paths. As a reminder: build tree is the path to target/output directory, source tree is the path at which your source code is located.

Understanding the basics

The compilation of C++ source code appears to be a fairly straightforward process. Let's take a small program, such as a classic hello.cpp application, as follows:
chapter-01/01-hello/hello.cpp
#include <iostream>
int main() {
std::cout << "Hello World!" << std::endl;
return 0;
}
Now, all we need to do to get an executable is to run a single command. We call the compiler with the filename as an argument:
$ g++ hello.cpp -o a.out
Our code is correct, so the compiler will silently produce an executable binary file that our machine can understand. We can run it by calling its name:
$ ./a.out
Hello World!
$
However, as our projects grow, you will quickly understand that keeping everything in a single file is simply not possible. Clean code practices recommend that files should be kept small and in well-organized structures. The manual compilation of every file can be a tiresome and fragile process. There must be a better way.

What is CMake?

Let's say we automate building by writing a script that goes through our project tree and compiles everything. To avoid any unnecessary compilations, our script will detect whether the source has been modified since the last time we ran it (the script). Now, we'd like a convenient way to manage arguments that are passed to the compiler for each file – preferably, we'd like to do that based on configurable criteria. Additionally, ...

Índice