c 链式困惑

标签 c variables scope linkage

我是中级 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/

相关文章:

无法连接到 Twitch IRC 服务器,IP 地址问题,C 语言

c - 声明一个字符串数组并选择一个字符

onload 函数内的 Javascript 变量范围

python - 列表与 int 分配 - "Every variable is a pointer"

c - c语言中如何比较两个矩阵的元素

c - 在同一个数组上重复找到最小值

python - 如何在多个 google appengine 实例上保持全局变量持久?

PHP 变量范围和 "foreach"

c++ - 是否可以在不编写复制构造函数的情况下在 main 中的构造函数之间进行选择?

import - 如何在 Elixir 1.0.3 中引用函数中的模块变量而不引用其模块?在其父范围内?