gpt4 book ai didi

c - 翻译单元中 `static` 定义和 `extern declaration` 的顺序

转载 作者:太空狗 更新时间:2023-10-29 17:21:27 25 4
gpt4 key购买 nike

我无法理解为什么这不起作用。

extern int i;

int main()
{
printf(" %d ", i);
}

static int i =3;

此外,这不起作用:

extern int i;

static int i =3;

int main()
{
printf(" %d ", i);
}

但是如果 static 变量是在 extern 声明 之前定义的,它会起作用:

static int i =3;

extern int i;

int main()
{
printf(" %d ", i);
}

据我所知,extern int i告诉我 i 出现在其他地方,这里看起来像(int i )

但是,其他地方意味着:

1) 也许,稍后指向作为全局变量相同翻译单元。

2) 也许,在一些other 翻译单元中。

我在想即使 static int i = 3i 的范围限制在当前,(1) 也是有效的定义它的翻译单元。

这里不是 static int i =3 global(我的意思是至少它在翻译单元中是可见的)即使它的翻译单元的范围有限?那为什么编译器找不到它呢?

当我编译前两个版本时,出现以下编译时错误:

 error: static declaration of ‘i’ follows non-static declaration
note: previous declaration of ‘i’ was here

我无法理解此错误消息。另外,为什么它提示它是一个静态的 declaration 难道它不是一个 definition 吗?

最佳答案

C11 6.2.2 标识符的链接第 4 节

For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible,31) if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration. If no prior declaration is visible, or if the prior declaration specifies no linkage, then the identifier has external linkage.

所以第二个声明将在第一个声明之后,回到您的示例,第一个和第二个示例 i 将有一个 extern 存储类。编译器认为这是一个错误。

而在第 3 个示例中,i 将是 static,因为 static 首先显示。那应该没问题。

并且,在 C11 的第 7 节 6.2.2 标识符的链接

If, within a translation unit, the same identifier appears with both internal and external linkage, the behavior is undefined.

所以最好不要在同一个翻译单元中用staticextern 声明同一个变量。

关于c - 翻译单元中 `static` 定义和 `extern declaration` 的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18142148/

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