Learning Hub Search Ctrl K

Legacy C++ › 2. Pointers, References and Memory

Preprocessor and Header Files

#include, #define, include guards, macros and their dangers.

beginner #preprocessor#macros#include-guards#headers

Explanation

The preprocessor runs before the compiler and does textual substitution:

  • #include <x> / #include "x": paste a file’s contents in. Angle brackets search system paths; quotes search the local directory first.
  • #define NAME value and function-like macros #define SQ(x) ((x)*(x)).
  • Conditional compilation: #if, #ifdef, #ifndef, #else, #endif.
  • Predefined macros: __FILE__, __LINE__, __DATE__, __cplusplus.

Header files hold declarations (class definitions, function prototypes, templates, extern variables); source files hold definitions. Every header needs include guards so it is processed once per translation unit.

Example

// ---- point.h ----
#ifndef POINT_H
#define POINT_H

struct Point {
    int x, y;
    Point(int x_, int y_) : x(x_), y(y_) {}
    int manhattan() const;       // declaration only
};

#endif // POINT_H

// ---- point.cpp ----
// #include "point.h"
// int Point::manhattan() const { return (x < 0 ? -x : x) + (y < 0 ? -y : y); }

A complete one-file program showing macros and conditional compilation:

#include <iostream>

#define SQUARE(x) ((x) * (x))     // parenthesize everything
#define DEBUG 1

int main() {
    int n = 3;
    std::cout << SQUARE(n + 1) << "\n";          // 16, thanks to the parentheses

#if DEBUG
    std::cout << "debug build, line " << __LINE__ << " of " << __FILE__ << "\n";
#endif

#ifdef _WIN32
    std::cout << "Windows\n";
#else
    std::cout << "Not Windows\n";
#endif
    return 0;
}

Common pitfalls

  • Macro side effects: SQUARE(i++) evaluates i++ twice. Macros do not respect scope or types.
  • Missing parentheses: #define DOUBLE(x) x * 2 makes DOUBLE(1 + 2) equal 1 + 2 * 2.
  • Defining variables or non-inline functions in headers causes multiple-definition link errors.
  • Circular includes: break them with forward declarations (class B;).
  • Never put using namespace std; in a header.

Legacy vs modern

Prefer const/constexpr over #define constants, inline/templates over function-like macros, and enum over macro lists. #pragma once is a widely supported alternative to guards; C++20 modules aim to replace headers.

Exercises

1. What happens if a header without include guards is included twice?

Its declarations are pasted twice, giving redefinition errors for classes and structs.

2. Replace #define MAX_USERS 50 with a typed alternative.

const int MAX_USERS = 50; (or constexpr int in C++11).