Germán Diago Germán Diago - 2 months ago 17
C Question

Macro generation depending on preprocessor conditionals

I have a situation like the following, where I have entries in a table with a macro:

#define FOR_MY_TYPES(apply) \
apply(a, b, c) \
apply(d, e, f) \
....


I also have some preprocessor conditionals:

#define CONDITION1 1
#define CONDITION2 0


I want that some entries in the table are added depending on these conditions, something like this:

#define FOR_MY_TYPES(apply) \
apply(a, b, c) \
#if CONDITION1 || CONDITION2
apply(x, y, z)
#endif


What is the best way to achieve this keeping only one macro definition, and, if possible, avoid duplicating entries depending on conditions. I want to avoid this:

#if CONDITION1
#define FOR_MY_TYPES(apply) \
....Full table here...
#endif
#if CONDITION2
#define FOR_MY_TYPES(apply) \
//Full table again + CONDITION2 types
#endif
#if CONDITION1 || CONDITION2
#define FOR_MY_TYPES(apply) \
//Full table again + CONDITION1 || CONDITION2 types
#endif


My problem is that there are quite a few combinations, so I should avoid replicating as much as possible. It is also more error-prone.

Answer

One possible approach:

#if CONDITION1 || CONDITION2
#define really_apply(x) x
#else
#define really_apply(x)
#endif

#define FOR_MY_TYPES(apply) \
    apply(a, b, c) \
    really_apply(apply(x, y, z))