C++ Preprocessor Use Or Replace

18 Apr 2022

[ c++  development  performance  ]

Format

#<directive> <stuff>

Allow command line flags

g++ test.cpp -DDEBUG_BUILD=true
if constexpr(DEBUG_BUILD) {
  ...
}

Directives do not have scope, the file is processed top down. So moving directives can change generated code.

Code exclusion antipatterns

Include

#include <file_to_include>

When to use:

Objects as macros

#define <identifier> <replacement>
#undef <identifier>

Reserved:

When to use:

Conditionals

#if <expr>
...
#elif <expr>
...
#else
...
#endif

When to use:

Function like macros

#define <identifier>(<arg1>, <arg2>)\
<replacement code>

When to use:

Variadic functions like macros

#define <identifier>(<arg1>, ...)\
 <replacement code>

When to use:

Remember:

do {
...
} while(0)

File and line info

When to use:

Stringification and Concatenation

#define <identifier>(<text>) #<text>

#define <identifier>(<text1>,<text2>) <text>##<text2>

When to use:

Pragma

#pragma

When to use:

Reference