Introduction & Environment Setup¶
Welcome to the Modern C++ Masterclass! This course is designed to take you from the basics of C++ to the advanced features of C++20 and C++23, specifically tailored for development on the Raspberry Pi.
What is C++?¶
C++ is a general-purpose programming language created by Bjarne Stroustrup. It is an extension of the C programming language, adding object-oriented features, generic programming, and direct memory manipulation.
Key Characteristics: - Performance: C++ is compiled directly to machine code, making it extremely fast. - Control: It gives you granular control over system resources and memory. - Portability: Standard C++ code can run on almost any platform, from microcontrollers to supercomputers.
Setting up the Environment¶
To write modern C++, we need a compiler that supports the latest standards (C++20/23). Raspberry Pi OS (Bookworm) comes with GCC 12, which is excellent.
1. Install Build Tools¶
Open your terminal and install the essential tools:
build-essential: Includesgcc,g++, andmake.cmake: A powerful build system generator.gdb: The GNU Debugger.
2. Verify Installation¶
Check that you have a recent version of GCC:
The Compilation Process¶
For a detailed explanation of the build process (preprocessing, compilation, linking), please refer to Part 4: Build Systems.
1. Preprocessing: Handles directives like #include and #define.
2. Compilation: Translates preprocessed code into assembly code.
3. Assembly: Converts assembly code into machine code (object files).
4. Linking: Combines object files and libraries into a single executable binary.
Your First Program: "Hello, World!"¶
Let's analyze a simple C++ program.
Modern C++ Style Guide¶
To write clean and efficient C++, follow these best practices from the start:
1. Avoid using namespace std;¶
It might seem convenient, but it pulls the entire standard library into the global namespace, causing naming conflicts.
2. Prefer \n over std::endl¶
std::endl not only prints a newline but also forces a buffer flush, which degrades performance. Use \n unless you strictly need an immediate flush.
3. The Future of Output: std::print (C++23)¶
C++23 introduces std::print (and std::println), a faster and more convenient way to print.
Note: This requires a very recent compiler (like GCC 14). For now, we stick to std::cout.
Building with CMake¶
While you can compile manually with g++ main.cpp -o app, CMake is the standard for managing complex projects.
Create a file named CMakeLists.txt:
Build Steps¶
- Create a build directory (to keep source clean):
- Generate build files:
- Compile:
- Run:
Basic Input/Output¶
Besides std::cout, we have std::cin for input.
Note: std::cin >> stops at whitespace. To read a full line, use std::getline(std::cin, name);.