Understanding static variables declaration/initial

2019-02-25 10:32发布

问题:

I have only one file in my project called test.c; the code below does not compile if I do not define "TRUE". I use vc. I just want to understand the behavior. Please throw some light on this aspect.

#ifdef TRUE
static int a; 
static int a = 1; 
#else 
static int a = 1; 
static int a; 
#endif 

int main (void) 
{ 
    printf("%d\n", a);
    return 0; 
}
-----------------------
#ifdef TRUE     // both ok
int a; 
int a = 1; 
#else           // both ok
int a = 1; 
int a; 
#endif

int main (void) 
{ 
    printf("%d\n", a);
    return 0; 
}

回答1:

That is because you can not declare a variable after you have defined it. However you may define a variable after you declare it.

#ifdef TRUE
static int a; //Declaring variable a
static int a = 1; //define variable a
#else 
static int a = 1; //define variable a
static int a; //Error! a is already defined so you can not declare it
#endif 


回答2:

Apparently, the compiler does not let you redefine a variable that has been initialized..



标签: c static linkage