int i; // A.
extern int i; // B.
I know A is a variable's definition. Namely, the compiler creates an object and assigns a block of memory to the variable i. But what is B? What's the difference between the definition and the declaration?
It's a declaration. It says there is an integer i that will be defined elsewhere.
Case A) is a 'tentative defintion' with external linkage. You can have multiple of these in a single translation unit, and all will refer to the same variable. The definition is called tentative because it will only zero-initialize the variable if there is no other definition with explicit initializer in the translation unit.
Case B) is a declaration but not a definition (tentative or otherwise), because there is no initializer present and no storage will be reserved. There must be a valid definition of the variable elsewhere in this or another translation unit. If there's a previous declaration of the variable with internal linkage in scope, the variable will have internal linkage, otherwise external, ie
static int foo;
extern int foo;
results in a valid tentative definition with internal linkage, whereas
extern int foo;
static int foo;
is invalid as you have a declaration with external linkage followed by a (tentative) definition with internal linkage.
See C99 sections 6.2.2 and 6.9.2 for details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With