gpt4 book ai didi

c++ - #ifdef 指令末尾的额外标记

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:54:59 25 4
gpt4 key购买 nike

为什么下面的代码可以编译?

#ifdef C++11
// ...
#endif

int main() {}

gcc 4.8.0 给我以下警告:

extra tokens at end of #ifdef directive

按照标准,宏名只能包含字母、数字和下划线字符。

也许是因为这个?

ISO/IEC 14882:2011

16.1 Conditional inclusion [cpp.cond]

6 Each directive’s condition is checked in order. If it evaluates to false (zero), the group that it controls is skipped: directives are processed only through the name that determines the directive in order to keep track of the level of nested conditionals; the rest of the directives’ preprocessing tokens are ignored, as are the other preprocessing tokens in the group. Only the first group whose control condition evaluates to true (nonzero) is processed. If none of the conditions evaluates to true, and there is a #else directive, the group controlled by the #else is processed; lacking a #else directive, all the groups until the #endif are skipped.151

我无法正确理解这句话。

最佳答案

就 C++ 而言,#ifdef C++11 是一个语法错误。没有规定编译器必须拒绝有语法错误的程序。

1.4 Implementation compliance [intro.compliance]

The set of diagnosable rules consists of all syntactic and semantic rules in this International Standard except for those rules containing an explicit notation that "no diagnostic is required" or which are described as resulting in "undefined behavior."

[...]

If a program contains a violation of any diagnosable rule or an occurrence of a construct described in this Standard as "conditionally-supported" when the implementation does not support that construct, a conforming implementation shall issue at least one diagnostic message.

警告是诊断信息。编译器完全有权继续成功编译程序,只要他们确保向您显示一条诊断消息。由于编译器历来接受此类指令,并且接受此类指令与标准的要求不冲突,因此他们继续这样做。

至少就 GCC 而言,您可以使用 -pedantic-errors 选项要求将所有标准要求的诊断设置为硬错误。

$ printf "#ifdef C++11\n#endif\n" | gcc -std=c++11 -pedantic-errors -E -x c++ -
# 1 "<stdin>"
# 1 "<command-line>"
# 1 "<stdin>"
<stdin>:1:9: error: extra tokens at end of #ifdef directive

关于c++ - #ifdef 指令末尾的额外标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15935073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com