传递包含特殊字符的预处理器标志 [c++17, g++]
我试图通过以下方式使用预处理器标志为 const char*
分配一个值。
#include <iostream>
#define ST(A...) #A
#define STR(A) ST(A)
const char* output = STR(FLAG);
int main() {
std::cout << output;
}
这种方法效果很好,除非 FLAG 包含一些特殊字符。当我尝试构建上述内容时,
g++ .\Main.cpp -std=c++17 -DFLAG="a,b!c)d}e-f"
我在错误日志中看到了这一点。它不喜欢特殊字符。
<command-line>: error: expected ',' or ';' before 'd'
.\Main.cpp:4:19: note: in definition of macro 'STR'
4 | #define STR(A) ST(A)
| ^
.\Main.cpp:6:26: note: in expansion of macro 'FLAG'
6 | const char* output = STR(FLAG);
| ^~~~
<command-line>: error: expected declaration before '}' token
.\Main.cpp:4:19: note: in definition of macro 'STR'
4 | #define STR(A) ST(A)
6 | const char* output = STR(FLAG);
| ^~~~
<command-line>: error: 'e' does not name a type
.\Main.cpp:4:19: note: in definition of macro 'STR'
4 | #define STR(A) ST(A)
| ^
.\Main.cpp:6:26: note: in expansion of macro 'FLAG'
6 | const char* output = STR(FLAG);
|
程序所需的输出将是 a,b!c)d}ef
。
是否有任何(合理的)方法可以使用预处理器标志或类似的东西来获取此功能?
I am trying to assign a value to a const char*
by using a pre-processor flag in the following way.
#include <iostream>
#define ST(A...) #A
#define STR(A) ST(A)
const char* output = STR(FLAG);
int main() {
std::cout << output;
}
This approach works well, unless FLAG contains some special characters. When I attempt to build the above with
g++ .\Main.cpp -std=c++17 -DFLAG="a,b!c)d}e-f"
I get this in the error log. It doesn't like the special characters.
<command-line>: error: expected ',' or ';' before 'd'
.\Main.cpp:4:19: note: in definition of macro 'STR'
4 | #define STR(A) ST(A)
| ^
.\Main.cpp:6:26: note: in expansion of macro 'FLAG'
6 | const char* output = STR(FLAG);
| ^~~~
<command-line>: error: expected declaration before '}' token
.\Main.cpp:4:19: note: in definition of macro 'STR'
4 | #define STR(A) ST(A)
6 | const char* output = STR(FLAG);
| ^~~~
<command-line>: error: 'e' does not name a type
.\Main.cpp:4:19: note: in definition of macro 'STR'
4 | #define STR(A) ST(A)
| ^
.\Main.cpp:6:26: note: in expansion of macro 'FLAG'
6 | const char* output = STR(FLAG);
|
The desired output of the program would be a,b!c)d}e-f
.
Is there any (sane) way to obtain this functionality using pre-processor flags, or something similar?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当
FLAG
是字符串时,您不必使用字符串化宏:实时演示
You don't have to use stringification macros when
FLAG
is a string:Live Demo