Preprocessor & headers
12 steps in 5 sets of C.
The preprocessor is a text substitution pass that runs before the compiler has any idea what your program means, and most of C's stranger corners live here. Macros, stringizing and token pasting, header guards and conditional compilation, and assert.
Twelve steps. Learn what it can do, then use rather less of it than you now know how to.
Macros
- Object-like macrosA define is textual substitution, done before the compiler sees your code.
- Why macros need parenthesesSubstitution ignores precedence, so every parameter and the whole body get brackets.
- The array length macroOne macro every C project has, and the one place it must not be used.
- static inline in headersA small function in a header must be static inline, or every including file collides.
Text manipulation
- Stringify and token pasteThe # operator turns an argument into a string, ## joins two tokens into one.
- Variadic macros__VA_ARGS__ forwards any number of arguments, which is how logging macros work.
- X-macrosOne list, several expansions: the table and the code stay in step by construction.
Headers & conditions
- Include guardsA header may be included many times, so it must protect itself.
- Conditional compilationThe preprocessor can include or drop whole regions based on what is defined.
Assertions
- assert and NDEBUGassert documents an invariant and checks it, until NDEBUG removes it entirely.
- Compile-time assertions_Static_assert checks a constant expression while compiling, so bad builds fail early.
Encore
- tour_header.cA header and its implementation in one file, showing the split a real project makes.