I have been searching for an hour about this seemingly obvious question, and read several other posts including this one with the same title, but I am still struggling to find a convincing answer. Please forgive my ignorance in advance, and consider this code:
#define MY_MACRO 1
#define IMPLEMENT(x) (defined(x) && (x))
#if IMPLEMENT(MY_MACRO)
#define TESTVAL 1
#else
#define TESTVAL 0
#endif
#include <stdio.h>
int main()
{
printf("Value is %d\n", TESTVAL);
return 0;
}
Which doesn't compile and the error messages are:
error: operator "defined" requires an identifier
error: missing '(' in expression
One of the answers in the linked thread says the argument of IMPLEMENT
is not known at compile-time, so we cannot use it with '#if defined'. But I don't think this is the case here. Can anyone explain why this doesn't compile?
Bonus question: is there any trick to safely replace the line #if defined(x) && x
?
CodePudding user response:
Can anyone explain why this doesn't compile?
IMPLEMENT(MY_MACRO)
is expanding MY_MACRO
to 1
and then replacing it for defined(1)
. defined(1)
is invalid. 1
is not an identifier.
is there any trick to replace the line #if defined(x) && x?
Yes, just use #if x
. If it's not defined, then it's zero. Just #if x
, no need for a defined.
#if MY_MACRO