I have a C program with a lot of optimizations that can be enabled or disabled with #define
s. When I run my program, I would like to know what macros have been
#ifdef MYMACRO
printf("MYMACRO defined: %d\r\n", MYMACRO);
#endif
I don't think what you are trying to do is possible. You are asking for info at runtime which has been processed before compilation. The string "MYMACRO" means nothing after CPP has expanded it to its value inside your program.
Why not simply testing it with the preprocessor ?
#if defined(X)
printf("%s is defined and as the value %d\n", #X, (int)X);
#else
printf("%s is not defined\n", #X);
#endif
One can also embed this in another test not to print it everytime:
#if define(SHOW_DEFINE)
#if defined(X)
printf("%s is defined and as the value %d\n", #X, (int)X);
#else
printf("%s is not defined\n", #X);
#endif
#endif
As long as you are willing to put up with the fact that SOMESTRING=SOMESTRING indicates that SOMESTRING has not been defined (view it as the token has not been redefined!?!), then the following should do:
#include <stdio.h>
#define STR(x) #x
#define SHOW_DEFINE(x) printf("%s=%s\n", #x, STR(x))
#define CHARLIE -6
#define FRED 1
#define HARRY FRED
#define NORBERT ON_HOLIDAY
#define WALLY
int main()
{
SHOW_DEFINE(BERT);
SHOW_DEFINE(CHARLIE);
SHOW_DEFINE(FRED);
SHOW_DEFINE(HARRY);
SHOW_DEFINE(NORBERT);
SHOW_DEFINE(WALLY);
return 0;
}
The output is:
BERT=BERT
CHARLIE=-6
FRED=1
HARRY=1
NORBERT=ON_HOLIDAY
WALLY=
This question is very close from Macro which prints an expression and evaluates it (with __STRING). Chrisharris' answer is very close from the answer to the previous question.
I believe what you are trying to do is not possible. If you are able to change the way your #define
s work, then I suggest something like this:
#define ON 1
#define OFF 2
#define OPTIMIZE_FOO ON
#define OPTIMIZE_BAR OFF
#define SHOW_DEFINE(val)\
if(val == ON) printf(#val" is ON\n");\
else printf(#val" is OFF\n");
you can use an integer variable initialized to 1. multiply the #define with this variable and print the value of variable.