wefwefa3
wefwefa3

Reputation: 4036

Weird behavior with extern and static linkage of variables

I found some behavior with extern and static (internal) variables that I find quite weird.

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?

Upvotes: 2

Views: 1177

Answers (1)

Ravichandra Sutrave
Ravichandra Sutrave

Reputation: 179

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.

Table to resolve conflicting linkages

Also from the standard section 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. If no prior declaration is visible, or if the prior declaration specifies no linkage, then the identifier has external linkage.

Hence the file a.c has all its external linkages resolved internally. Your code has defined x as static first and then as external in the translation unit a.c. Hence linkage is internal from the table above. So it prints 24.

Upvotes: 5

Related Questions