是否可以在 C 中打印预处理器变量?
是否可以将 C 中预处理器变量的值打印到 stderr? 例如,我现在拥有的是:
#define PP_VAR (10)
#if (PP_VAR > 10)
#warning PP_VAR is greater than 10
#endif
但我想做的是:
#define PP_VAR (10)
#if (PP_VAR > 10)
#warning PP_VAR=%PP_VAR%
#endif
在C中可能有这样的事情吗?
Is is possible to print to stderr the value of a preprocessor variable in C? For example, what I have right now is:
#define PP_VAR (10)
#if (PP_VAR > 10)
#warning PP_VAR is greater than 10
#endif
But what I'd like to do is:
#define PP_VAR (10)
#if (PP_VAR > 10)
#warning PP_VAR=%PP_VAR%
#endif
Is something like this possible in C?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以在 Visual Studio 下打印出预处理器变量的值。 以下打印出 _MSC_VER 的值:
但不确定这有多标准。
You can print out the value of a preprocessor variable under visual studio. The following prints out the value of _MSC_VER:
Not sure how standard this is though.
这适用于 GCC 4.4.3:
产生:
This works with GCC 4.4.3:
yields:
许多 C 编译器支持
#warning
,但它不是由 C 标准定义的,除非您使用 C23 或更高版本。然而,GCC 至少不会对后面的数据进行预处理,这意味着很难看到变量的值。
GCC 制定:
C23 标准预计会说明:
由于它指定诊断消息包含预处理标记,因此宏不会在
#error
或#warning
的消息中展开。 指定#error
的标准均未明确指定如果执行该指令,翻译单元的编译应失败 — 仅应生成诊断信息。 然而,有一个合理的预期是,如果执行#error
指令,TU应该无法编译。 相比之下,执行#warning
指令不应导致 TU 编译失败。Many C compilers support
#warning
, but it is not defined by the C standard unless you're using C23 or later.However, GCC at least does not do pre-processing on the data that follows, which means it is hard to see the value of a variable.
GCC produces:
The C23 standard is expected to say:
Since it specifies that the diagnostic message includes the preprocessing tokens, macros will not be expanded in the message for either
#error
or#warning
. None of the standards that specify#error
explicitly specify that the compilation of the translation unit should fail if the directive is executed — only that a diagnostic shall be produced. Nevertheless, there is a reasonable expectation that if a#error
directive is executed, the TU should fail to compile. By contrast, executing a#warning
directive should not cause the compilation of the TU to fail.使用预处理器标记粘贴运算符:##TOKEN_NAME
如前所述,您使用的预处理器指令是非标准的,所以 YMMV。
Use the preprocessor token-pasting operator: ##TOKEN_NAME
As previously noted, the preprocessor directives you are using are non-standard, so YMMV.
好吧,你所做的实际上是不标准的。 首先,
#warning
或#warn
指令不是标准的。 其次,使用预处理器时,该行必须以井号开头,没有任何空格:由于您已经在使用非标准扩展,因此您需要查找您正在使用的特定预处理器/编译器的文档看看它是如何描述
#warning
的。Well, what you are doing is actually non-standard. Firstly, the
#warning
or#warn
directive is not standard. Secondly, when using the preprocessor, the line must begin with the pound symbol, without any spaces:Since you are already using a non-standard extension, you will need to look up the documentation of the particular preprocessor/compiler that you are using to see what it says about
#warning
.