I regularly use object-like preprocessor macros as boolean flags in C code to turn on and off sections of code.
For example
#define DEBUG_PRINT 1
And then use it like
#if(DEBUG_PRINT == 1)
printf("%s", "Testing");
#endif
However, it comes a problem if the header file that contains the #define
is forgotten to be included in the source code. Since the macro is not declared, the preprocessor treats it as if it equals 0, and the #if
statement never runs.
When the header file is forgotten to be included, non-expected, unruly behaviour can occur.
Ideally, I would like to be able to both check that a macro is defined, and check that it equals a certain value, in one line. If it is not defined, the preprocessor throws an error (or warning).
I'm looking for something along the lines of:
#if-def-and-true-else-throw-error(DEBUG_PRINT)
...
#endif
It's like a combination of #ifdef
and #if
, and if it doesn't exist, uses #error
.
I have explored a few avenues, however, preprocessor directives can't be used inside a #define
block, and as far as I can tell, there is no preprocessor option to throw errors/warnings if a macro is not defined when used inside a #if
statement.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…