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 #if !defined(MYVARIABLE) || #MYVARIABLE == "" ... blablabla ... #endif
EDIT: 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 user forgot to define this string.
## is Token Pasting Operator. The double-number-sign or "token-pasting" operator (##), which is sometimes called the "merging" operator, is used in both object-like and function-like macros.
The double-number-sign or token-pasting operator (##), which is sometimes called the merging or combining operator, is used in both object-like and function-like macros. It permits separate tokens to be joined into a single token, and therefore, can't be the first or last token in the macro definition.
Description. In the C Programming Language, the #ifdef directive allows for conditional compilation. The preprocessor determines if the provided macro exists before including the subsequent code in the compilation process.
All Preprocessor directives begin with the # (hash) symbol. C++ compilers use the same C preprocessor. The preprocessor is a part of the compiler which performs preliminary operations (conditionally compiling code, including files etc...) to your code before the compiler sees it.
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>
#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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With