katang
katang

Reputation: 2774

How to define a macro that expands to a conditional statement in C++?

I want to create some context-sensitive macros. The macro

 #define LOG_WARNING(x) qWarning()().noquote().nospace() << x

works fine, it is located in file Macros.h. I want to define a macro, which does not print log messages when called from unit testing routine. So, I modified like

#define LOG_INFO(x) if(!UNIT_TESTING) qInfo().noquote().nospace() << x

Since in this way the macro will depend on UNIT_TESTING, I provided in the same Macros.h

extern bool UNIT_TESTING;   // Whether in course of unit testing

However, the compilers tells

declaration does not declare anything [-fpermissive]
 extern bool UNIT_TESTING; // Whether in course of unit testing
        ^

At the same time, if the external is declared in the file from which Macros.h is included, it works fine. Do I wrong something?

Upvotes: 0

Views: 125

Answers (1)

schorsch312
schorsch312

Reputation: 5694

Here is how to share variables across source files. Nevertheless, I would highly recommend not to do so, but to implement a function (bool IS_UNIT_TESTING() ) or class which takes care of this. In this way you can change the implementation without changing the interface.

Moreover, Macros are evil. They are error prone can not be debuged easily. Use inline functions or constexp instead. The compiler will optimize it to almost the very same code.

Upvotes: 2

Related Questions