The C preprocessor and macros
#include, #define, include guards and conditional compilation, plus why macros need parentheses.
Before compiling, the preprocessor handles lines starting with #:
#includepastes in a header file.#define NAME valuereplaces text. Function-like macros such as#define SQUARE(x) ((x) * (x))need parentheses around every parameter and the whole body, because they paste text rather than evaluate expressions.#if,#ifdefand#ifndefinclude code only under certain conditions.
Headers use include guards (#ifndef MY_H / #define MY_H / #endif, or #pragma once) so being included twice doesn't cause errors. In C++, prefer constexpr and inline functions to macros.
Example
#include <stdio.h>
#define SQUARE(x) ((x) * (x))
#define DEBUG 1
int main(void) {
printf("%d\n", SQUARE(2 + 1));
#if DEBUG
printf("debug build\n");
#endif
return 0;
}
Output:
9
debug build