- Basic macros.
- Overload macro on number of arguments.
- Style
- For each macro
- Compare strings in
#if - Nesting same macros.
- Creating function templates.
In this article I will shortly show the most common preprocessor patterns that I use.
The preprocessor patterns emerged from my work on StackOverflow. People often ask very similar questions with problems that can be solved in C preprocessor similarly. In this article I will shortly show the common preprocessor patterns that I use and discuss the form and style that I use to write in preprocessor.
Basic macros.
#define CONCAT(a, b) a##b
#define XCONCAT(a, b) CONCAT(a, b)
#define STRINGIFY(a) #a
#define XSTRINGIFY(a) STRINGIFY(a)
The X in front should be read as eXpand.
Lately some additions to the C standard preprocessor have been proposed in n3190.
Overload macro on number of arguments.
Macro overload without _0 case:
#define MACRO_1(a) printf("%s\n", #a)
#define MACRO_2(a, b) printf("%s %s\n", #a, #b);
#define MACRO_3(a, b, c) printf("%s %s %s\n", #a, #b, #c);
#define MACRO_4(a, b, c, d) printf("%s %s %s %s\n", #a, #b, #c, #d);
#define MACRO_N(_4,_3,_2,_1,N,...) MACRO##N
#define MACRO(...) MACRO_N(##__VA_ARGS__, _4,_3,_2,_1)(__VA_ARGS__)
Macros MACRO_1 up to MACRO_4 I am calling “overload candidates”.
Macro MACRO_N I am calling “overload resolving macro”.
Macro MACRO calls “overload resolving macro” to choose proper “overload candidate”.
Macro overload with _0 case:
#define MACRO_0()
#define MACRO_1(a) printf("%s\n", #a)
#define MACRO_2(a, b) printf("%s %s\n", #a, #b);
#define MACRO_3(a, b, c) printf("%s %s %s\n", #a, #b, #c);
#define MACRO_4(a, b, c, d) printf("%s %s %s %s\n", #a, #b, #c, #d);
// What I call "overload resolving macro".
#define MACRO_N(_4,_3,_2,_1,_0,N,...) MACRO##N
// Calling "overload resolving macro" to choose proper overload condidate.
#define MACRO(...) MACRO_N(_0, ##__VA_ARGS__, _4,_3,_2,_1)(__VA_ARGS__)
The above macro is non-standard because it uses ##__VA_ARGS__ GNU extension. This could be changed to MACRO_N(_0 __VA_OPT__(,) __VA_ARGS__,, but it will then not work on older compilers.
Style
- There has to be at least two spaces between the
)ending macro parameter
list and macro replacement. - There have to be at least two spaces between the end of macro text in
replacement list and backslash\for the next line. - Macro arguments should be separated by spaces.
- Except in the case of decreasing numbers list when overloading macro on number of
arguments, in which case no spaces is permissible for increased readability.
- Except in the case of decreasing numbers list when overloading macro on number of
- When overloading a macro on number of arguments:
- Put the least numbered overload definition first.
- The overload resolving macro
MACRO_Nends with a trailing_N. - The argument list in the definition of overload resoling macro
MACRO_N
and in the call to this macro should be decreasing numbers prefixed with_. - Nowadays still prefer
MACRO_N(_0, ##__VA_ARGS__)over__VA_OPT__(,)for
compatibility with older compilers.
- Prefer to reduce the number of replacements the macro has to expand to be
fully expanded.- It helps debugging and greatly increases readiness of compiler messages.
In long and nested replacements of macros, in case of error there are
many “in expansion of” compiler messages, which make it hard to find the
actual error or type. By reducing the number of expansions, it is much
easier to debug and find errors in the code.
- It helps debugging and greatly increases readiness of compiler messages.
- Never write macros that expand to unbalanced
(,),{or}parentheses.
For each macro
#define FOREACH_1(f, a) f(a)
#define FOREACH_2(f, a, ...) f(a) FOREACH_1(f, __VA_ARGS__)
#define FOREACH_3(f, a, ...) f(a) FOREACH_2(f, __VA_ARGS__)
#define FOREACH_4(f, a, ...) f(a) FOREACH_3(f, __VA_ARGS__)
#define FOREACH_N(_4,_3,_2,_1,N,...) FOREACH##N
#define FOREACH(f, __VA_ARGS__) FOREACH_N(__VA_ARGS__,_4,_3,_2,_1)(f__VA_ARGS__)
Compare strings in #if
Create a dictionary of all possible strings that you want to handle with some prefix. Every dictionary item expands to a number. The dictionary element should not be 0, as undefined macros are replaced by 0 in the context of #if. Concatenate the string with the prefix and compare with the number from the dictionary. That way preprocessor will do integer comparison which it is capable to.
// Compile with gcc -E -DTYPE=float or -DTYPE=double
#define CONCAT(a, b) a##b
#define XCONCAT(a, b) CONCAT(a, b)
// Dictionary.
#define TYPE_float 1
#define TYPE_double 2
// Comparison checking function.
#define TYPE_COMPARE(x, y) XCONCAT(TYPE_, x) == XCONCAT(TYPE_, y)
#if TYPE_COMPARE(TYPE, float)
#warning Code uses float
#elif TYPE_COMPARE(TYPE, double)
#warning Code uses doubles.
#else
#error TYPE is not defined properly.
#endif
Nesting same macros.
Because expanded macros in the chain are painted blue, they can’t be re-used. It effectively means, that it is not possible to chain macros. For example, doing FOREACH(FOREACH will not work properly.
The simplest, most reliable, most maintainable way of nesting is to just re-declare the macro chain with the same functionality but different name. Although there is code repetitions, I think it is a fair price to be very maintainable and easy to sync. Functionality. Just copy the code and rename the macro.
// User compiles with -DTYPE=float or -DTYPE=double
// FOREACH macro with one cookie.
#define FOREACH_1(f, c, a) f(c, a)
#define FOREACH_2(f, c, a, ...) f(c, a) FOREACH_1(f, c, __VA_ARGS__)
#define FOREACH_3(f, c, a, ...) f(c, a) FOREACH_2(f, c, __VA_ARGS__)
#define FOREACH_N(_3,_2,_1,N,...) FOREACH##N
#define FOREACH(f, c, ...) FOREACH_N(__VA_ARGS__,_3,_2,_1)(f, c, __VA_ARGS__)
// Repeated FOREACH macro but named FOREACH2.
#define FOREACH2_1(f, c, a) f(c, a)
#define FOREACH2_2(f, c, a, ...) f(c, a) FOREACH2_1(f, c, __VA_ARGS__)
#define FOREACH2_3(f, c, a, ...) f(c, a) FOREACH2_2(f, c, __VA_ARGS__)
#define FOREACH2_N(_3,_2,_1,N,...) FOREACH2##N
#define FOREACH2(f, c, ...) FOREACH2_N(__VA_ARGS__,_3,_2,_1)(f, c, __VA_ARGS__)
// Generate pairs of numbers.
#define PRINT(i, j) {i, j},
// Given a number, pair it with 20 and 21.
#define CB(_, i) FOREACH(PRINT, i, 20, 21)
struct ints { int a, b; };
struct ints arr1[] = { FOREACH(CB, _, 10, 11) };
// ^^ Expands to:
// struct ints arr1[] = { FOREACH(PRINT, 10, 20, 21) FOREACH(PRINT, 11, 20, 21) };
// Because the call trace is:
// FOREACH -> CB -> FOREACH
// The inner call to FOREACH is not expanded, because it's painted blue by the first call.
struct ints arr2[] = { FOREACH2(CB, _, 10, 11) };
// ^^ Expadns to:
// struct ints arr2[] = { {10, 20}, {10, 21}, {11, 20}, {11, 21}, };
Creating function templates.
There are multiple ways of creating function templates in C programming language using C preprocessor.
Using macro expansion.
Single macro with static functions.
The simplest there is, is to write a single macro to expand to a function definition. All the definitions should be static so they can be included in multiple files.
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#define CONCAT(a, b) a##b
#define XCONCAT(a, b) CONCAT(a, b)
#define DEFINE_ARRAY(N, T, FMT) \
\
struct XCONCAT(N, _array) { \
T *elems; \
size_t s; \
}; \
\
static inline int XCONCAT(N, _array_push)(struct XCONCAT(N, _array) *this, T e) { \
void *pnt = realloc(this->elems, this->s + 1); \
if (!pnt) return -ENOMEM; \
this->elems = pnt; \
this->elems[this->s] = e; \
this->s++; \
return 0; \
} \
\
static inline void XCONCAT(N, _array_print)(struct XCONCAT(N, _array) *this) { \
for (size_t i = 0; i < this->s; ++i) { \
if (i != 0) { \
putchar(' '); \
} \
printf(FMT, this->elems[i]); \
} \
putchar('\n'); \
} \
\
static inline void XCONCAT(N, _array_free)(struct XCONCAT(N, _array) *this) { \
free(this->elems); \
} \
\
/* */
DEFINE_ARRAY(int, int, "%d")
DEFINE_ARRAY(double, double, "%.1f")
int main() {
struct int_array ia = {0};
int_array_push(&ia, 1);
int_array_push(&ia, 2);
int_array_print(&ia);
int_array_free(&ia);
//
struct double_array da = {0};
double_array_push(&da, 1.5);
double_array_push(&da, 2.5);
double_array_print(&da);
double_array_free(&da);
}
// outputs:
// 1 2
// 1.5 2.5
Split function declaration and definitions.
For a good measure, you would want to split function declaration and definitions from such a macro into separate macros. This is some work.
However, bottom line nowadays compilers working on 4 gigahertz CPUs with gigabytes of memory, I do not believe it is worth it. In C++, templates are usually compiled when instantiated, just like static functions in C. Using explicit installations of templates in C++ is not that common and doesn’t handle all cases. Templates instantiated upon use are normal.
Separate file with template
If your template functions become longer and bigger, managing them inside a single expanding macro with a long lines of \ and comments only inside /* is become a real challenge. Searching for bugs and typing errors in such code is a real pain to go through.
*/
The other way is to create a separate file where forward defined macros are replaced before including the file. First define macros that the file will use, then include the file. This allows the implementation to define additional macros and manage easier and more visually appealing, allowing also to find bugs in the code easier.
This is also the development that STC project. On the beginning STC used macros that expand client side. Then it replaced it by including files with defined macros.
// array.h
// Note - no include guard.
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
// template paramteers
#if __IDE__
// Provide definitions for IDE.
#define a_PREFIX prefix
#define a_TYPE int
#define a_FMT "%d"
#endif
#ifndef a_PREFIX
#error a_PREFIX is not defined
#endif
#ifndef a_TYPE
#error a_TYPE is not defined
#endif
#ifndef a_FMT
#error a_FMT is not defined
#endif
#ifndef CONCAT
#define CONCAT(a, b) a##b
#endif
#ifndef XCONCAT
#define XCONCAT(a, b) CONCAT(a, b)
#endif
#define i_MEMB(x) XCONCAT(a_PREFIX, _array_##x)
#define i_TYPE XCONCAT(a_PREFIX, _array)
struct i_TYPE {
a_TYPE *elems;
size_t s;
};
static inline int i_MEMB(push)(struct i_TYPE *self, a_TYPE e) {
void *pnt = realloc(self->elems, self->s + 1);
if (!pnt) return -ENOMEM;
self->elems = pnt;
self->elems[self->s] = e;
self->s++;
return 0;
}
static inline void i_MEMB(print)(struct i_TYPE *self) {
for (size_t i = 0; i < self->s; ++i) {
if (i != 0) {
putchar(' ');
}
printf(a_FMT, self->elems[i]);
}
putchar('\n');
}
static inline void i_MEMB(free)(struct i_TYPE *self) {
free(self->elems);
}
#undef a_TYPE
#undef a_PREFIX
#undef a_FMT
#undef i_TYPE
#undef i_MEMB
Then you can compile with:
// main.c
#define a_PREFIX int
#define a_TYPE int
#define a_FMT "%d"
#include "array.h"
#define a_PREFIX double
#define a_TYPE double
#define a_FMT "%.1f"
#include "array.h"
int main() {
struct int_array ia = {0};
int_array_push(&ia, 1);
int_array_push(&ia, 2);
int_array_print(&ia);
int_array_free(&ia);
//
struct double_array da = {0};
double_array_push(&da, 1.5);
double_array_push(&da, 2.5);
double_array_print(&da);
double_array_free(&da);
}
Note how we can still use preprocessor in array.h. This can be used to introduce much better logic into the implementation by still utilizing preprocessor conditional for code generation. Because the macros becomes tangled – some come from user definitions as parameters, some from the internal implementation of the code – I recommend using namespace in naming convention to differentiate.
After the declarations are instantiated from the file, all macros are #undef, so that the header can be reused again.