Chapter 1: Tooling and Environment Setup

The C++ Compilation Model

Unlike interpreted languages, C++ requires compilation. Understanding this process is fundamental:

┌──────────────┐    ┌──────────────┐    ┌──────────────┐    ┌──────────────┐
│  Source Code │───▶│ Preprocessor │───▶│   Compiler   │───▶│    Linker    │
│   (.cpp/.h)  │    │   (#include) │    │  (Assembly)  │    │ (Executable) │
└──────────────┘    └──────────────┘    └──────────────┘    └──────────────┘
                           │                    │                    │
                           ▼                    ▼                    ▼
                    Expanded source      Object files (.o)    Final binary

Step-by-Step Process

  1. Preprocessor: Handles #include, #define, #ifdef directives
  2. Compiler: Converts C++ to assembly, then to object files
  3. Linker: Combines object files into executable, resolves symbols

Major Compilers

CompilerPlatformCommandNotes
GCCLinux, macOS, Windowsg++Most common on Linux
ClangAll platformsclang++Better error messages
MSVCWindowsclVisual Studio's compiler

Installing on Linux (Ubuntu/Debian)

# Install GCC and essential build tools
sudo apt update
sudo apt install build-essential

# Install Clang (optional but recommended)
sudo apt install clang

# Verify installation
g++ --version
clang++ --version

Installing on macOS

# Install Xcode Command Line Tools (includes Clang)
xcode-select --install

# Or install via Homebrew for latest GCC
brew install gcc

# Verify
clang++ --version
g++-13 --version  # Homebrew GCC uses versioned names

Installing on Windows

Option 1: MSYS2 (Recommended)

# Download and install MSYS2 from https://www.msys2.org/
# Then in MSYS2 terminal:
pacman -S mingw-w64-x86_64-gcc mingw-w64-x86_64-cmake

Option 2: Visual Studio

  • Install Visual Studio with "Desktop development with C++" workload
  • Use Developer Command Prompt for cl access

Your First C++ Program

Create a file called hello.cpp:

#include <iostream>

int main() {
    std::cout << "Hello, C++ World!" << std::endl;
    return 0;
}

Compiling and Running

# Compile with GCC
g++ hello.cpp -o hello

# Compile with Clang
clang++ hello.cpp -o hello

# Run
./hello

Essential Compiler Flags

# Always use these during development:
g++ -Wall -Wextra -Werror -std=c++20 -g hello.cpp -o hello

# Flag breakdown:
# -Wall        Enable common warnings
# -Wextra      Enable extra warnings
# -Werror      Treat warnings as errors (strict mode)
# -std=c++20   Use C++20 standard (or c++17, c++23)
# -g           Include debug symbols
# -o hello     Output filename

Optimization Flags (for release builds)

# Optimization levels:
g++ -O0 ...  # No optimization (default, fastest compile)
g++ -O1 ...  # Basic optimization
g++ -O2 ...  # Recommended for release
g++ -O3 ...  # Aggressive optimization
g++ -Os ...  # Optimize for size

IDE and Editor Setup

  1. Install VS Code

  2. Install extensions:

    • C/C++ (Microsoft) - IntelliSense, debugging
    • C/C++ Extension Pack - Additional tools
    • CMake Tools - CMake integration
  3. Create .vscode/tasks.json for building:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Build C++",
            "type": "shell",
            "command": "g++",
            "args": [
                "-Wall",
                "-Wextra",
                "-std=c++20",
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}
  1. Create .vscode/launch.json for debugging:
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Debug C++",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}/${fileBasenameNoExtension}",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb"
        }
    ]
}

CLion (Professional IDE)

JetBrains CLion is excellent for C++ but requires a license. It includes:

  • Advanced refactoring
  • Built-in CMake support
  • Excellent debugging
  • Static analysis

Vim/Neovim

For terminal users, set up with:

  • clangd for LSP (Language Server Protocol)
  • coc.nvim or nvim-lspconfig for integration

Essential Development Tools

Debuggers

# GDB (GNU Debugger) - Works with GCC
sudo apt install gdb

# LLDB - Works better with Clang
sudo apt install lldb

Basic GDB Usage:

# Compile with debug symbols
g++ -g program.cpp -o program

# Start debugger
gdb ./program

# Common commands:
# run           - Start program
# break main    - Set breakpoint at main()
# break 42      - Set breakpoint at line 42
# next          - Step over
# step          - Step into
# print x       - Print variable x
# backtrace     - Show call stack
# continue      - Continue execution
# quit          - Exit

Static Analyzers

# Clang-Tidy (static analysis and linting)
sudo apt install clang-tidy

# Run analysis
clang-tidy myfile.cpp -- -std=c++20

# Cppcheck (another static analyzer)
sudo apt install cppcheck
cppcheck --enable=all myfile.cpp

Memory Debugging

# Valgrind - Memory leak detection
sudo apt install valgrind

# Run with leak checking
valgrind --leak-check=full ./program

# AddressSanitizer (compile-time, faster)
g++ -fsanitize=address -g program.cpp -o program
./program  # Will report memory errors

Formatting

# clang-format - Code formatter
sudo apt install clang-format

# Format a file
clang-format -i myfile.cpp

# Create .clang-format in project root for style settings

Example .clang-format:

BasedOnStyle: Google
IndentWidth: 4
ColumnLimit: 100

Project Structure Best Practices

For a typical C++ project:

my_project/
├── CMakeLists.txt       # Build configuration
├── README.md
├── .clang-format        # Code style
├── .clang-tidy          # Linter config
├── src/                 # Source files
│   ├── main.cpp
│   └── module.cpp
├── include/             # Header files
│   └── module.h
├── tests/               # Unit tests
│   └── test_module.cpp
├── build/               # Build output (gitignored)
└── third_party/         # External dependencies

Quick Reference: Compile Commands

# Simple single file
g++ -std=c++20 -Wall main.cpp -o main

# Multiple files
g++ -std=c++20 -Wall main.cpp utils.cpp -o program

# With include directory
g++ -std=c++20 -Wall -I./include src/*.cpp -o program

# Debug build
g++ -std=c++20 -Wall -g -O0 main.cpp -o main_debug

# Release build
g++ -std=c++20 -Wall -O2 -DNDEBUG main.cpp -o main_release

# With library linking
g++ main.cpp -lpthread -o program  # Link pthread library

Exercises

  1. Setup Verification

    • Install GCC or Clang on your system
    • Compile and run the hello world program
    • Try both g++ and clang++ if possible
  2. Compiler Flags Exploration

    • Compile a program with -Wall and without, and see the difference
    • Create a deliberate warning and make -Werror catch it
  3. Debugger Introduction

    • Compile a simple program with -g
    • Set a breakpoint and step through it with GDB

Previous: 00 - Introduction Next: 02 - Basic Syntax and Fundamentals