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

标签 c posix language-lawyer

我只是切线地处理了一个错误报告,其中一个软件不正确地做 #include <sched.h>在函数体内,我无法找到说明这不是有效用法的权威文本。对于标准 C 头文件,我能找到的最接近的是 7.1.2 ¶4:

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

但我什至不完全清楚这应该如何解释,当然它不包括 POSIX-only header ,如 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, ...

如果允许包含在 block 作用域中,那么使用标准方法处理多个包含保护的任何实现都无法满足该要求,但我希望看到更清晰的东西,以及 POSIX 中的东西。

最佳答案

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

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

所以程序文本(“翻译单元”)只是一系列外部定义。这与“外部链接”中使用“外部”一词无关。如该部分第 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 中的限制适用于文件范围内的任何声明或定义。 (我不知道为什么标准说“外部声明或定义”,因为外部定义集是外部声明的子集。但我不明白该短语如何被解读为排除任何外部声明,即使恰好不是定义的声明。)

在 Posix 中,基本相同的限制出现在第 2.2 节(编译环境)末尾的系统接口(interface)第 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.

链接:

关于c - C 和 POSIX 在哪里指定标准 header 必须包含在文件范围内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52528550/

相关文章:

c# - 自动滚动控件(WinAPI)?

c - ioctl 参数大小限制

c++ - 将日期时间转换为毫秒 - C++ - 跨平台

c++ - 为什么 pthread_cond_wait 需要锁?

c++ - 为什么 std::exchange 不是 noexcept?

python - pandas.DataFrame.groupby 能保证稳定吗?

c - 删除一个元素后堆栈弹出操作不起作用

awk - 如何使用 POSIX shell 脚本删除文件的特​​定行?

javascript - 带有公共(public)的顶级 var 语句与带有逗号 : why are they different 的赋值语句

c - "The C standards set lower bounds on the numeric ranges of the different data types, but there are no upper bounds"?