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

Solution 1:

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

Solution 2:

I haven't seen this solution to the problem but am surprised it is not in common use . It seems to work in Xcode Objc. Distinguish between "defined with no value" and "defined set 0"

#define TRACE
#if defined(TRACE) && (7-TRACE-7 == 14)
#error TRACE is defined with no value
#endif

Solution 3:

I want to make sure that the project fails to compile if user forgot to define this string.

While i'd check this in a previous build-step, you can do this at compile-time. Using Boost for brevity:

#define A "a"
#define B
BOOST_STATIC_ASSERT(sizeof(BOOST_STRINGIZE(A)) > 1); // succeeds
BOOST_STATIC_ASSERT(sizeof(BOOST_STRINGIZE(B)) > 1); // fails