How to test if preprocessor symbol is #define#39;d but has no value?(如何测试预处理器符号是否已#defined 但没有值?)
问题描述
使用 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
我这样做的原因是因为我正在处理的项目应该通过 /DMYSTR=$(MYENVSTR)
/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 宏魔法:
#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 的值是空字符串:
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);
这篇关于如何测试预处理器符号是否已#define'd 但没有值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何测试预处理器符号是否已#define'd 但没有值?
基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01