Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 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 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.

like image 959
galets Avatar asked Sep 23 '10 18:09

galets


People also ask

What does ## mean in preprocessor?

## 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.

What does ## mean in C preprocessor?

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.

Is #ifdef a preprocessor in C?

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.

Which is the preprocessor symbol?

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.


2 Answers

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); 
like image 86
Martin York Avatar answered Sep 28 '22 10:09

Martin York


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 
like image 31
Ian Brackenbury Avatar answered Sep 28 '22 11:09

Ian Brackenbury