How to test if preprocessor symbol is #define'd but has no value?

前端 未结 9 1394
渐次进展
渐次进展 2020-11-30 06:08

Using C++ preprocessor directives, is it possible to test if a preprocessor symbol has been defined but has no value? Something like that:

#define MYVARIABLE         


        
9条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 06:58

    Soma macro magic:

    #define DO_EXPAND(VAL)  VAL ## 1
    #define EXPAND(VAL)     DO_EXPAND(VAL)
    
    #if !defined(MYVARIABLE) || (EXPAND(MYVARIABLE) == 1)
    
    Only here if MYVARIABLE is not defined
    OR MYVARIABLE is the empty string
    
    #endif
    

    Note if you define MYVARIABLE on the command line the default value is 1

    g++ -DMYVARIABLE 
    

    Here the value of MYVARIABLE is 1

    g++ -DMYVARIABLE= 
    

    Here the value of MYVARIABLE is the empty string

    The quoting problem solved:

    #define DO_QUOTE(X)        #X
    #define QUOTE(X)           DO_QUOTE(X)
    
    #define MY_QUOTED_VAR      QUOTE(MYVARIABLE)
    
    std::string x = MY_QUOTED_VAR;
    std::string p = QUOTE(MYVARIABLE);
    

提交回复
热议问题