Reputation: 709
I was wondering if there's a way to combine #define and #ifndef macro..
What this means is that I want to use #ifndef macro within the #define macro..
Since it's kind of hard to explain,, this is an example of what I want to do:
#define RUN_IF_DEBUG \
#ifndef DEBUG_MODE \
; // do nothing \
#else \
cout << "Run!" << endl; \
#endif
int main() {
RUN_IF_DEBUG
}
So I want the RUN_IF_DEBUG macro to run ONLY IF the DEBUG_MODE is defined...
Is there a way to do this?
Upvotes: 2
Views: 1050
Reputation: 1
Simply do
#ifndef DEBUG_MODE
#define RUN_IF_DEBUG ; // do nothing
#else
#define RUN_IF_DEBUG cout << "Run!" << endl;
#endif
You can't put other preprocessor statements within a macro's body.
As from the c++ standards definitionsdraft section
16 Preprocessing directives
...
control-line:
...
# define
identifier replacement-list new-line
# define
identifier lparen identifier-listopt) replacement-list new-line
# define
identifier lparen ... ) replacement-list new-line
# define
identifier lparen identifier-list, ... ) replacement-list new-line
These are the allowed syntax variants for#define
statements.
`
Upvotes: 2
Reputation: 409176
The problem is the line-continuation in the macro. What they do is put everything on a single line, so the expanded macro will look something like
int main() {
#ifndef DEBUG_MODE ; #else cout ...; #endif
}
This will not work very well with the preprocessor or the compiler.
Instead you should switch the nesting, and use #ifndef
first, and #define
the macros in the inner level.
Upvotes: 0
Reputation: 15997
It is usually done the other way around:
#ifndef DEBUG_MODE
# define RUN_IF_DEBUG ;
#else
# define RUN_IF_DEBUG cout << "Run!" << endl;
#endif
Upvotes: 5