Is it possible to write custom conditional pre-processor directives in C. for example;
#define _IF_ (condition, explanation) \
#ifdef condition
Every comment would be great, thanks.
Is it possible to write custom conditional pre-processor directives in C. for example;
#define _IF_ (condition, explanation) \
#ifdef condition
Every comment would be great, thanks.
No.
The #define preprocessor directive can not emit another preprocessor directive (like #ifdef) because the #ifdef is not at the start of the line.
Preprocessing directives are lines in your program that start with
#. The#is followed by an identifier that is the directive name. For example,#defineis the directive that defines a macro. Whitespace is also allowed before and after the#.
The closest I could get to an elegant syntax is this.
#define _IF_(condition,explanation) condition
#if _IF_(1 == 2,"A False Case")
"This should not appear"
#endif
#if _IF_(1 == 1,"A True Case")
"This should appear"
#endif
Demonstrated here : https://godbolt.org/z/JFljOm
Although this macro may have a better label.
If you really need to get this syntax for some reason and you are willing to modify your build system a little.
You can run your code though the preprocessor twice to allow for this double expansion.
However, a preprocessor macro also can't emit the # character, so we'll use the ??= trigraph to circumvent this.
// File a.prec
#define _IF_(condition, explanation) \
??=if condition
#define _ELSE_ ??=else
#define _ENDIF_ ??=endif
_IF_(1==1,"Yep")
"This Text"
_ENDIF_
_IF_(2==1,"Nope")
"Not This Text"
_ENDIF_
Compiling with just the -E flag gives us. https://godbolt.org/z/sJIScN
??=if 1==1
"This Text"
??=endif
??=if 2==1
"Not This Text"
??=endif
We then need to enable -trigraphs on the main compile step to parse the ??= as a #. Giving us the desired output of :
https://godbolt.org/z/-0rqe5
"This Text"
This solution will give you problems with normal includes as using the preprocessor twice isn't safe, so you'll need to use the ??= trigraph on anything you only want to happen in the normal compile step.