Printing name and value of a macro

前端 未结 11 2557
别跟我提以往
别跟我提以往 2020-12-28 21:46

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

相关标签:
11条回答
  • 2020-12-28 22:08
    #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.

    0 讨论(0)
  • 2020-12-28 22:08

    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
    
    0 讨论(0)
  • 2020-12-28 22:09

    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=
    
    0 讨论(0)
  • 2020-12-28 22:12

    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.

    0 讨论(0)
  • 2020-12-28 22:18

    I believe what you are trying to do is not possible. If you are able to change the way your #defines 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");
    
    0 讨论(0)
  • 2020-12-28 22:20

    you can use an integer variable initialized to 1. multiply the #define with this variable and print the value of variable.

    0 讨论(0)
提交回复
热议问题