1

This is a theoretical question: Assume I have 2 source files / compilation units, A.c and B.c

A.c:

int x;

B.c:

int x;

The variable x is considered to be shared between the objects. That is, one int was allocated somewhere and this variable is global and visible to all source files that declare it.

However I can also do this: B.c:

extern int x;

Is there any difference between extern and plain global variables in this context? And what is the difference in general?

Thanks!!

Vladimir Gazbarov
  • 860
  • 1
  • 10
  • 25
  • 2
    See [What are extern variables in C?](http://stackoverflow.com/questions/1433204/what-are-extern-variables-in-c/1433387#1433387) for a lot of information. Your A.c and B.c code (with `int x;` twice) only works as a common extension (recognized in Annex J of the C standard). The variant with `extern int x;` matches the standard's requirements. – Jonathan Leffler Jun 24 '13 at 14:08

2 Answers2

2

If you have one definitions of x in A.c and one definition of x in B.c your program invokes undefined behavior.

Some toolchains will accept your program by defining the undefined behavior in some particular cases but you cannot rely on this for all compilers.

C99, 6.9p5) "If an identifier declared with external linkage is used in an expression (other than as part of the operand of a sizeof 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"

ouah
  • 142,963
  • 15
  • 272
  • 331
1

The difference is that it won't link without extern, you'll get a multiple definition error. Only the version with extern works.

Guillaume
  • 10,463
  • 1
  • 33
  • 47