Reputation: 1215
Is there anyway to define/run a macro on specific condition in C++?
My application takes some parameters on running, say ./test -l
I want to define a macro if -l is provided as a parameter, so I tried:
if (strcmp(argv [2],"-l")==0)
#define LOOPBACK
but it's wrong. My application is always defining LOOPBACK
!!
Upvotes: 0
Views: 84
Reputation: 1974
Preprocessor macros perform text substitution, and the output of the preprocessor is then compiled as code.
That means, by definition, that macros can only be defined, redefined, undefined or expanded at (strictly speaking, before) compile time. There is no way for a macro to have a different expansion based on runtime data.
It also means that macros don't honour any rules of scope.
Which is why your LOOPBACK macro is always defined - the expansion is unrelated to the if
statement.
Upvotes: 2
Reputation: 119
All preprocessor directives (e.g: #include
, #define
, ...) are performed/ evaluated by the preprocessor, which runs before the compiler. So the macro you're defining is defined without knowing about the if(...)
statement.
Upvotes: 1