How do you enable “#ifndef/#endif” blocks in makefile builds?
Question
I'm trying to enable debugging options in MuPDF. For some reason they have used #ifndef NDEBUG
and #endif
greying out code I want to use. I searched throughout the library but couldn't find any traces of NDEBUG defined anywhere. I've managed to work around this by adding #undef NDEBUG
in a header, but I would like to know if there is a more non-intrusive method to do so.
SO, can you enable "#ifndef/#endif" blocks from the makefile?
Also, why would you use #ifndef
to grey out code? Isn't it supposed to be #ifdef NDEBUG
?
Solution
You can add -DNDEBUG to the following 3 variables - CFLAGS, CPPFLAGS and CXXFLAGS in your Makefile to define NDEBUG. Which is equivalent to adding #define NDEBUG
There are other variations too:
-DNBDEBUG=1
is equivalent to
#define NDEBUG 1
And to answer the question of why would someone use #ifndef instead of #ifdef is because it highlights your modifications to the original code much clearly.
For example consider the following code as the original version:
int a = 123;
int b = 346;
int c = a + b;
And you need to add a macro DO_MULT which will multiply instead - there are 2 ways to do this.
First Variation:
int a = 123;
int b = 346;
#ifdef DO_MULT
int c = a *b;
#else
int c = a + b;
#endif
Second variation:
int a = 123;
int b = 346;
#ifndef DO_MULT
int c = a + b;
#else
int c = a *b;
#endif
If you use difftools to see the changes - the second variation will show the diff more clearly compared to the first one.
One more reason why you would use a #ifndef is to DO something in CATCH-ALL-EXCEPT scenarios.
OTHER TIPS
#ifndef
won't omit the code if the flag is defined, hence it's usage. You've managed to include the code using #undef
.
Both #ifdef
and #ifndef
are useful, as justification consider this contrived example: you have a bunch of debug printf
code that you only want to compile into a Debug build, using #ifdef DEBUG
conditions. In the same executable you also have code that you want to leave out of a Debug build. In this case using #ifndef DEBUG
is your only choice.
You can define such flags in the makefile, and you can also try to remove previous definitions by using -U
. Look for a CFLAGS
variable in the makefile and add -UNDEBUG
, or add it directly to the compiler call in the compilation target.
If the flag is being defined somewhere in the source tree then this won't help.