Catalog / C Preprocessor Cheatsheet
C Preprocessor Cheatsheet
A comprehensive cheat sheet for the C preprocessor, covering directives, macros, conditional compilation, and more. This guide provides a quick reference for developers working with C and C++.
Directives Overview
Include Directives
|
Searches standard system directories for |
|
Searches the current directory first, then standard system directories. |
|
If |
Example: |
|
Define and Undefine
|
Defines a simple symbol. Commonly used for conditional compilation. |
|
Defines a symbol with a value. The value can be any text. |
|
Undefines a previously defined symbol. |
Example: |
|
Conditional Compilation
|
|
|
|
Macros in Detail
Basic Macros
|
A simple macro that doubles its argument. |
Example Usage: |
|
Important: |
Always enclose macro arguments in parentheses to avoid unexpected behavior due to operator precedence. |
Stringification Operator (#)
|
Converts a macro parameter into a string literal. |
Example: |
|
Token Pasting Operator (##)
|
Concatenates two tokens into a single token. |
Example: |
|
Variadic Macros
|
Creates macros that accept a variable number of arguments. |
Example: |
|
Predefined Macros
Standard Predefined Macros
|
The name of the current input file, as a string literal. |
|
The current line number in the input file, as a decimal integer. |
|
The date of compilation, as a string literal in “Mmm dd yyyy” format. |
|
The time of compilation, as a string literal in “hh:mm:ss” format. |
|
Indicates that the implementation conforms to the C standard. Defined as 1. |
Example Usage: |
|
Compiler-Specific Macros
Compilers often define their own macros (e.g., |
These can be used for compiler-specific conditional compilation. |
Example: |
|
Advanced Directives and Techniques
Error and Warning Directives
|
Causes the preprocessor to issue a fatal error message and halt compilation. |
|
Causes the preprocessor to issue a warning message, but compilation continues. |
Example: |
|
Pragma Directive
|
Specifies various compiler-specific instructions. Behavior varies between compilers. |
Common Usage: |
|
Line Control
|
Resets the line number and filename reported by the compiler for subsequent code. |
Example: |
|