c++visual-c++c-preprocessor

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


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

#define MYVARIABLE
#if !defined(MYVARIABLE) || #MYVARIABLE == ""
... blablabla ...
#endif

The reason why I am doing it is because the project I'm working on is supposed to take a string from the environment through /DMYSTR=$(MYENVSTR), and this string might be empty. I want to make sure that the project fails to compile if the user forgot to define this string.


Solution

  • Ssome 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 <file>
    

    Here the value of MYVARIABLE is the empty string:

    g++ -DMYVARIABLE= <file>
    

    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);