-1
extern int a = 10; // it is not giving error
int main ()
{
 extern int b = 10; //it is giving error
 return 0;
}

error: ‘b’ has both ‘extern’ and initializer extern int b = 10;

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • what is the use of extern keyword? – Gopala krishna Jan 05 '17 at 10:59
  • @Artur Hmmm... I think an extern declaration is possible inside a function and refers to a global object (with external linkage!) defined elsewhere. Same e.g. for local function declarations. I suppose it cannot be initialized though because that's only possible at the point of *definition*, i.e. where the memory gets allocated. – Peter - Reinstate Monica Jan 05 '17 at 11:03
  • @Garf365 correct, but that is C++, this is C. Can we get a C dupe, I believe it will be there. :) – Sourav Ghosh Jan 05 '17 at 11:28
  • Read [this](http://stackoverflow.com/q/1433204/2173917) question and answers. – Sourav Ghosh Jan 05 '17 at 11:46
  • 1
    @kiner_shah: Just read that post. Not only it contains a lot of babble and does not go straight to the point, it also contains some wrong statements and claims. It also is incomplete, as it seems not to cover `inline` functions which are often missunderstood. – too honest for this site Jan 05 '17 at 12:06
  • @Olaf, Wow! Thanks for letting me know :-), otherwise I would have blindly followed that! This [link](http://stackoverflow.com/questions/10422034/when-to-use-extern-in-c) seems ok, I guess! – kiner_shah Jan 05 '17 at 12:07

1 Answers1

1

Referring to C11 (N1570) 6.7.9/5 Initialization:

If the declaration of an identifier has block scope, and the identifier has external or internal linkage, the declaration shall have no initializer for the identifier.

The rule is placed within constraints section, so any conforming compiler should reject the code, that violates it.

The point of extern keyword at the block scope is to declare some existing object from outside scope. It would not make much sense to declare an object and give it some other value at the point of declaration.

The recommended way of declaring external objects is to put their declarations at the file scope (at the top of source code), thus they are easy to spot and manage by maintenance programmer.

Grzegorz Szpetkowski
  • 36,988
  • 6
  • 90
  • 137