The foll code
gave no error on gccCode:static int a;
extern int a;
But the foll gave error :But I think in case of global variables 'int' and 'extern' int are same or not??Code:static int a;
int a;
Printable View
The foll code
gave no error on gccCode:static int a;
extern int a;
But the foll gave error :But I think in case of global variables 'int' and 'extern' int are same or not??Code:static int a;
int a;
extern is a declaration that does not define the variable (does not actually allocate the variable). it is used when you want to refer to a variable from another file. so you can declare 'extern int a;' in the same file as the definition of int a; such as if an include file has 'extern int a;' to declare it for other files. but the second example tries to define the variable twice, which is not allowed.
but the catch in your first example is using 'static' on the definition of 'a'. so what you are actually saying is 'i have a local static variable named 'a', and I also have a declaration of an extern variable 'a' from some other file'. thats an interesting idea. which 'a' is used locally?
in Visual Studio 2012, it prints '1'. so the local static value hides the global extern.Code:// a.c
#include <stdio.h>
extern int a;
static int a = 1;
int main( void )
{
printf("%d\n",a);
return 0;
}
// b.c
int a = 2;
then another catch: if instead of 'extern int a;', you say 'extern int a = 0', you get a definition instead of just a declaration. so you would get a redefinition error if you said
i don't have the standard handy. can someone point out the clause(s) in the standard?Code:static int a;
extern int a = 0;
This is pretty much the same question as http://cboard.cprogramming.com/c-pro...variables.html with just a slightly different context.