简体   繁体   English

用不完整类型定义struct的结构

[英]Tentative definition of struct with incomplete type

Consider the following as a C file: 将以下内容视为C文件:

static struct S a;

int main() {
  return (long)&a;
}

struct S {
  int b;
} s;

Based on my reading of the C11 spec , I believe this is undefined behavior. 基于我对C11规范的阅读,我认为这是未定义的行为。 6.9.2 states: 6.9.2州:

A declaration of an identifier for an object that has file scope without an initializer, and without a storage-class specifier or with the storage-class specifier static, constitutes a tentative definition. 具有没有初始化程序的文件范围且没有存储类说明符或存储类说明符为静态的对象的标识符声明构成暂定定义。

and under a Semantics heading (not Constraints): 并在Semantics标题下(不是约束):

If the declaration of an identifier for an object is a tentative definition and has internal linkage, the declared type shall not be an incomplete type. 如果对象的标识符声明是暂定定义并且具有内部链接,则声明的类型不应是不完整的类型。

It seems that the declaration on the first line is a tentative definition, and that the object a has internal linkage, and yet struct S has incomplete type at the time of the declaration. 似乎第一行的声明是一个暂定的定义,并且对象a具有内部链接,但struct S在声明时具有不完整的类型。 So, I would expect this to violate the second quotation, thus resulting in undefined behavior. 所以,我希望这会违反第二个引用,从而导致未定义的行为。

However, GCC does not print any diagnostic when run with the --std=c11 -Wall -pedantic flags. 但是,使用--std=c11 -Wall -pedantic标志运行时,GCC不会打印任何诊断。 Am I misunderstanding the standard, or does GCC not print a diagnostic for this type of undefined behavior? 我是否误解了标准,或者GCC没有为这种类型的未定义行为打印诊断信息?

Yes this is undefined. 是的,这是未定义的。

Undefined behavior is just what the term indicates, it is not defined by the standard. 未定义的行为正如该术语所指示的那样,它不是由标准定义的。 Any compiler may add its own definitions and thereby extend the standard, and is not obliged to diagnose any of them. 任何编译器都可以添加自己的定义,从而扩展标准,并且没有义务诊断它们中的任何一个。 In particular, gcc has some special ideas about tentative definitions. 特别是,gcc对暂定定义有一些特殊的想法。 Code that uses these is not portable. 使用这些的代码不可移植。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM