- 平台:Ubuntu 14.04 LTS
- 编译器:GCC 4.8.2 (Ubuntu 4.8.2-19ubuntu1)
我正在编写一个需要向后投诉 C90 的 header 。如果编译器支持 C99 或 C11,我会包含一些可选函数。所以我使用标准功能测试宏。我只想知道我这样做的方式是否正确。
#if __STDC__
//code
#endif
#if __STDC_VERSION__ >= 199000L
//code
#endif
#if __STDC_VERSION__ >= 201100L
//code
#endif
我假设如果编译器是严格的 C90 或 C89,那么编译器会出错并说 __STDC_VERSION__
is undefined 我是对的吗?如果是这样,我应该使用 defined() 吗?例如 #if defined(__STDC__)
而不仅仅是 #if __STDC__
。
最佳答案
如果预处理器条件中未定义的标识符不是 define
的参数,则它们将被替换为 0,因此没有错误:
6.10.1 Conditional inclusion
3 Preprocessing directives of the forms
#if constant-expression new-line groupopt #elif constant-expression new-line groupopt
check whether the controlling constant expression evaluates to nonzero.
4 Prior to evaluation, macro invocations in the list of preprocessing tokens that will become the controlling constant expression are replaced (except for those macro names modified by the defined unary operator), just as in normal text. If the token defined is generated as a result of this replacement process or use of the defined unary operator does not match one of the two specified forms prior to macro replacement, the behavior is undefined. After all replacements due to macro expansion and the defined unary operator have been performed, all remaining identifiers (including those lexically identical to keywords) are replaced with the pp-number 0, and then each preprocessing token is converted into a token. [...]
您可以使用#error
指令强制编译错误。
关于C 标准版本检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26279906/