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.
#if DEBUG_PRINT == 1
. In the case whereDEBUG_PRINT
is not defined, this becomes#if 0 == 1
, which is the behavior you want. – DamaralandDEBUG_PRINT == 1
in a header file, but forgotten to#include
it in the .c file. – Mackenziemackerelprint
function in a macro or another function, rather than wrapping it at all of the call locations. Then you can consolidate the error generation code in a single place rather than trying to sprinkle it all over your project. – Pretended#if-def-and-true-else-throw-error(DEBUG_PRINT)
instead of#if DEBUG_PRINT == 1
, so even if this feature existed it wouldn't achieve anything useful. – Bonnybonnyclabbergcc
has an option (-Wundef
) to generate a warning when an undefined identifier is evaluated in an#if
directive. – Champollion