int i; // A.
extern int i; // B.
I know A is a variable's definition. Namely, the compi开发者_如何学运维ler 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.
The extern keyword introduces a variable declaration, not a definition. It says that somewhere in some source file there will be a variable defined with the given declaration, which allows the source file to reference the variable without hassle, but doesn't actually define the variable. This allows one variable defined in one file to be shared and accessed across multiple source files without each file having its own independent copy.
B states that the variable i
is defined elsewhere, typically in a different translation unit. The Wikipedia article would not be a bad place to continue your research.
A) As well as declaring the variable i, it is actually implicit definition of i.
B) A declaration of i. You will need the variable i to be defined some where.
精彩评论