Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing name and value of a macro

I have a C program with a lot of optimizations that can be enabled or disabled with #defines. When I run my program, I would like to know what macros have been defined at compile time.

So I am trying to write a macro function to print the actual value of a macro. Something like this:

SHOW_DEFINE(X){\
  if( IS_DEFINED(X) )\
      printf("%s is defined and as the value %d\n", #X, (int)X);\
  else\
      printf("%s is not defined\n", #X);\
}

However I don't know how to make it work and I suspect it is not possible, does anyone has an idea of how to do it?

(Note that this must compile even when the macro is not defined!)

like image 625
Ben Avatar asked Jul 22 '09 11:07

Ben


1 Answers

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=
like image 157
Dipstick Avatar answered Sep 18 '22 13:09

Dipstick