gpt4 book ai didi

c 链式困惑

转载 作者:太空狗 更新时间:2023-10-29 15:16:56 24 4
gpt4 key购买 nike

我是中级 C 程序员。我正在浏览一个简单的 C 代码片段

int a ; // A
const int b; // B
static int c; //C
void func(int d) // D
{
//.....
}

变量a,b,c,d的联系是什么。我很确定 a 默认有外部链接,bcd 有内部链接。我的理解正确吗?

这是我在这个网站上的第一个问题。

最佳答案

来自 C99 的 6.2.2,标识符的链接 部分,权威来源:

1/ An identifier declared in different scopes or in the same scope more than once can be made to refer to the same object or function by a process called linkage. There are three kinds of linkage: external, internal, and none.

2/ In the set of translation units and libraries that constitutes an entire program, each declaration of a particular identifier with external linkage denotes the same object or function. Within one translation unit, each declaration of an identifier with internal linkage denotes the same object or function. Each declaration of an identifier with no linkage denotes a unique entity.

3/ If the declaration of a file scope identifier for an object or a function contains the storage-class specifier static, the identifier has internal linkage.

4/ For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible, 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.

5/ If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the storage-class specifier extern. If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.

6/ The following identifiers have no linkage: an identifier declared to be anything other than an object or a function; an identifier declared to be a function parameter; a block scope identifier for an object declared without the storage-class specifier extern.

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

现在,一个一个地处理你的变量:

  • a 包含在第 5 部分中,因为它是“具有文件范围且没有存储类说明符的对象的标识符”。因此它具有外部链接。
  • b 也包含在第 5 部分(文件范围,无存储类说明符)中。因此外部链接。
  • c 包含在第 3 部分中,因为它具有 static 存储类说明符 - 它具有内部链接。
  • 最后,第 6 部分介绍了 d,它是一个函数参数 - 它没有链接。

关于c 链式困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5295639/

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