Josh
Josh

Reputation: 21

Difference between declaration of variable with extern and without it

1.h

extern int a;

1.c

#include <stdio.h>
#include "1.h"

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

2.c

#include "1.h"

int a = 6;

This compiles and runs just fine (gcc 1.c 2.c) if you remove extern from 1.h and prints 6. I know that removing it might cause a to be defined in every translation unit (object file), but what is the problem? doesn't the linker just git rid of it when linking since it compiles with no errors?

Upvotes: 0

Views: 56

Answers (1)

Josh
Josh

Reputation: 21

This technique does not conform to the letter of the C standard and the 'one definition rule' — it is officially undefined behaviour:

J.2 Undefined behavior

An identifier with external linkage is used, but in the program there does not exist exactly one external definition for the identifier, or the identifier is not used and there exist multiple external definitions for the identifier (6.9).

§6.9 External definitions ¶5

An external definition is an external declaration that is also a definition of a function (other than an inline definition) or an object. If an identifier declared with external linkage is used in an expression (other than as part of the operand of a sizeof or _Alignof operator whose result is an integer constant), somewhere in the entire program there shall be exactly one external definition for the identifier; otherwise, there shall be no more than one.161)

161) Thus, if an identifier declared with external linkage is not used in an expression, there need be no external definition for it.

more here: How do I use extern to share variables between source files?

Upvotes: 2

Related Questions