Reputation: 1458
Recently while learning about c programming i noticed something that i found interesting. I had read that a statement like int i=0;
is the only way to force a definition while a statement like extern int i;
implies a forced declaration. A statement like int i;
would be context dependent. But what happens when i combine the the extern with initialization like extern int i=13;
. Compiler generates a warning. But what is this rule governing this?
Upvotes: 8
Views: 310
Reputation: 43748
In C, a definition is just a declaration that happens to allocate storage (whether it is because it has an initializer, or because it is a tentative definition that gets used as a definition). So, everything that you can do to a declaration (like specifying it has extern
storage), you can also do to a definition.
Note that this differs from C++.
Upvotes: 0
Reputation: 2613
When you declare a variable you just bind a name to it.
When you define a variable you reserve memory for it.
When you declare a variable as extern you are telling the compiler "this is defined elsewhere and will be available on linking time", so it's OK to use it.
Upvotes: 4
Reputation: 206646
This is a Coding style warning.
The argument for this is the code is valid, but extremely unidiomatic for C since "extern" is generally expected to mean that the declaration is not providing a definition of the object.
extern int i=13;
declares and defines i
, While:
extern int i;
just declares the variable i
.
A specific bug 45977 has been raised on GCC on the same but it is still shows Unconfirmed Status.
The bug report points out that the code is syntactically as per the C standard. And it has an discussion which discusses this in detail.
For Standerdese Fans:
Relevant Section References are:
ansi c99 Standard 6.2.2: Linkage Of Identifiers and
ansi c99 Standard 6.9.2.4
Upvotes: 5
Reputation: 4085
Extern is used if you want to access particular variable from different program. As you don't have any definition for that in you program your complier is giving you an error.
Upvotes: 0