简体   繁体   English

具有变量外部和静态链接的怪异行为

[英]Weird behavior with extern and static linkage of variables

I found some behavior with extern and static (internal) variables that I find quite weird. 我发现一些extern变量和static (内部)变量的行为使我觉得很奇怪。

Here is an example: 这是一个例子:

/* file a.c */
#include <stdio.h>

/* variable with static linkage */
static int x = 24;

int f() {
        /* variable with extern linkage */
        extern int x; 
        return x;
}

int main() {
        printf("%d\n", f());
        return 0;
}

- -

/* file x.c */
/* define symbol `x` to be an `int` equal to 100 */
int x = 100;

I compile this program using: 我使用以下命令编译该程序:

$ cc a.c x.c -o a

I then run my program and get this output: 然后,我运行程序并获得以下输出:

$ ./a
24

Why does this program output 24 and not 100 ? 为什么此程序输出24而不是100

Quoting from link 引用链接

The following table identifies the linkage assigned to an object that is declared twice in a single translation unit. 下表列出了分配给在单个转换单元中声明两次的对象的链接。 The column designates the first declaration, and the row designates the redeclaration. 列指定第一个声明,行指定重新声明。

用于解决冲突链接的表

Also from the standard section 6.2.2: 同样来自标准第6.2.2节:

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. 对于在可见该标识符的先前声明的范围内用存储类说明符extern声明的标识符,如果该先前声明指定了内部或外部链接,则该标识符在后面的声明中的链接与该链接相同在事先声明中指定。 If no prior declaration is visible, or if the prior declaration specifies no linkage, then the identifier has external linkage. 如果没有在先声明可见,或者在先声明没有指定链接,则标识符具有外部链接。

Hence the file ac has all its external linkages resolved internally. 因此,文件ac在内部解决了所有外部链接。 Your code has defined x as static first and then as external in the translation unit ac Hence linkage is internal from the table above. 您的代码先将x定义为静态,然后将其定义为转换单元ac中的外部。因此,上表中的链接是内部的。 So it prints 24 . 因此它打印24

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

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