C/C++ Arena

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 #:

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

Practice it