C Preprocessor and Macros

C Preprocessor and Macros

Conditional compilation, include guards, predefined macros, macro forms, and the main preprocessor directives in C and C++.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

C Preprocessor and Macros

Core directives

Common macro shapes

Object-like macros

#define BUFFER_SIZE 1024

Function-like macros

#define MAX(a, b) ((a) > (b) ? (a) : (b))

Stringification and token pasting

#define STR(x) #x
#define JOIN(a, b) a##b

Predefined macros you will see often

Include guards and conditional compilation

#ifndef WIDGET_H
#define WIDGET_H

/* declarations */

#endif

Modern C++ code may also use #pragma once, but include guards remain the portable baseline pattern.

Macro risks

When macros are still appropriate

Prefer language features when possible

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}