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¶
Unlike interpreted languages (like Python), C++ code must be compiled before it can run. This process has four main stages:
- Preprocessing: Handles directives starting with
#(like#include). It copies header files into your source file. - Compilation: Translates C++ code into assembly language.
- Assembly: Translates assembly into machine code (object files
.o). - Linking: Combines object files and libraries into a single executable binary.
Your First Program: "Hello, World!"¶
Let's analyze a simple C++ program.
Code Breakdown¶
// ...: These are comments. The compiler ignores them. -//for single-line comments. -/* ... */for multi-line comments.#include <iostream>: Tells the preprocessor to include the standard Input/Output stream library. This allows us to usestd::cout.int main() { ... }: Every C++ program must have exactly onemainfunction. Execution starts here.std::cout: Represents the Standard Output (usually the terminal).<<: The insertion operator. It sends the string "Hello..." tocout.std::endl: Inserts a newline character and flushes the buffer.return 0;: Returns the exit status to the operating system.0typically means "success".
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);.