C 和 POSIX 在哪里指定标准 headers 必须包含在文件范围内?

Where do C and POSIX specify that standard headers have to be included at file scope?

我刚刚处理了一个错误报告,其中一个软件在函数的 body 中错误地执行了 #include <sched.h>,但我找不到权威的文本来说明这不是有效用法。对于标准 C headers,我能找到的最接近的是 7.1.2 ¶4:

If used, a header shall be included outside of any external declaration or definition, ...

但我什至不完全清楚这应该如何解释,当然它不包括 POSIX-only headers 像 sched.h.

从上面的文字中可以清楚地看出:

Standard headers may be included in any order; each may be included more than once in a given scope, with no effect different from being included only once, ...

如果允许包含在块作用域中,那么使用标准方法对多个包含防护的实现都无法满足该要求,但我希望看到更清楚的内容,以及 POSIX 中的内容。

为了清楚下面引用的子句的措辞,回想一下 external declaration 是在 C 语法中定义的(§6.9,外部定义

translation-unit:
    external-declaration
    translation-unit external-declaration
external-declaration:
    function-definition
    declaration

所以程序文本("translation unit")只是一系列的外部定义。这与 "external linkage" 中 "external" 一词的使用无关。如该节第 4 段所述:

…the unit of program text after preprocessing is a translation unit, which consists of a sequence of external declarations. These are described as “external” because they appear outside any function (and hence have file scope).

因此,问题中引用的 §7.1.2¶4 中的限制适用于文件范围内的任何声明或定义。 (我不知道为什么标准说 "external declaration or definition",因为外部定义集是外部声明的子集。但我不明白如何读取该短语以排除任何外部声明,即使是碰巧不是定义。)

在 Posix 中,基本相同的限制出现在系统接口第 2 章(一般信息)的第 2.2 节(编译环境)末尾:

If used, the application shall ensure that a header is included outside of any external declaration or definition, and it shall be first included before the first reference to any type or macro it defines, or to any function or object it declares. However, if an identifier is declared or defined in more than one header, the second and subsequent associated headers may be included after the initial reference to the identifier. Prior to the inclusion of a header, the application shall not define any macros with names lexically identical to symbols defined by that header.

Link: