如何测试预处理符号是否是#define'd但没有值? [英] How to test if preprocessor symbol is #define'd but has no value?

查看:264
本文介绍了如何测试预处理符号是否是#define'd但没有值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C ++预处理器指令,可以测试预处理器符号是否已定义,但没有值?像这样:

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:我这样做的原因是因为我工作的项目应该通过 / DMYSTR = $(MYENVSTR)从环境中获取一个字符串。 ,并且此字符串可能为空。

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.

推荐答案

Soma macro magic:

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

注意,如果在命令行上定义MYVARIABLE,默认值为1

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

g++ -DMYVARIABLE <file>

这里MYVARIABLE的值为1

Here the value of MYVARIABLE is 1

g++ -DMYVARIABLE= <file>

这里MYVARIABLE的值是空字符串

Here the value of MYVARIABLE is the empty string

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

这篇关于如何测试预处理符号是否是#define'd但没有值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆