I am coding a C++ program and I am trying to include a debug messaging method controlled by a macro which is only called when a debugging flag is set in run time when creating the object which owns the debugging method. The performance is important, so I am trying the debug messaging code not to be called if it is not needed, instead of compiling two different versions of the program, one with debugging macro and another one without.
Until now I was trying something like this:
unsigned int flag = 0xFFFFFFFF;
if (flag != 0)
{
#define DEBUG
}
#ifdef DEBUG
debug("This is call 1 to the debug method");
#endif
#ifdef DEBUG
debug("This is call 2 to the debug method");
#endif
debug(std::string message)
{
if ((flag && MASK_I_DEFINED_SOMEWHERE_FOR_STUFF) != 0)
{
std::cout << message << std::endl;
}
}
I use masks to show debugging information only in specific moments of the run time, or only for specific objects of the class. Everything seemed to work right, because if flag is 0, it does not output any message, but I found out that it doesn't matter the value of flag when defining DEBUG, this program always defines DEBUG. If the flags are 0, it does not print anything, but the debug method is called anyway and the checks are performed, which means a loose in performance.
I also tried with something like the following example, to keep the structure of my code:
#define FLAG flag
#if FLAG>0
#define DEBUG
#endif
But in this case, the #if returns always false, no matter the value of flag.
I even tried with:
const int flag2 = flag;
#define FLAG flag2
#if FLAG>0
#define DEBUG
#endif
with same results as the example above. My question is: Is there a way of defining a macro depending on the value of a variable? Any ideas are welcome, but please keep in mind that I would like to keep this structure. Otherwise it would mean changing thousands if lines of code.
Thank you all, guys.
#definehappen even before compilation, during the pre-processing step. You cannot affect this at run-time.