开发者

static extern vs extern static

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

#ifdef TRUE
static int a;
extern int a;
#else
extern int a;
static int a;
#endif

int main (void)
{
  a =10;
  printf("%开发者_StackOverflowd", a);
  return 0;
}


When TRUE is not defined, the first declaration (extern) says a has external linkage (ISO/IEC 9899:1999, 6.2.2, paragraph 4, no prior declaration). The second declaration (static) states a has internal linkage (paragraph 3). An identifier cannot have both internal and external linkage (paragraph 7).

In the TRUE defined case, the extern in the second declaration has no impact because there is a prior declaration declaring a with internal linkage (paragraph 4).

See draft of ISO/IEC 9899:1999.


I am not sure what you're trying to do here, but you are re-declaring a as both a static and external variable, in different order.

When applied to a variable, static allows global variables to only be visible within that file. extern declares an external variable, defined elsewhere. So for example you would declare a as extern if it was originally defined in a separate file, and declare it as static if it should only be visible within this file itself.

Here are the errors:

test.c:8:12: error: static declaration of ‘a’ follows non-static declaration
test.c:7:12: note: previous declaration of ‘a’ was here

You declare a as an external variable (defined in a different file), but then re-declare it as static, only visible within this file.

In this case I would review what those storage classes (extern, static, etc) mean and then decide how your variable should be declared.


When you define TRUE, you are declaring a as extern, which means definition of a is in some other file, but compiler couldn't find it, so it can't compile your file.

Also, I think you wrote wrong in question, this file should be compiled when you don't define TRUE.


The problem here is when you do not define TRUE using #define TRUE, the compiler while executing the #else part encounters first the 'extern' declaration of variable 'a' and starts anticipating its declaration in an external scope somewhere. Remember the memory for extern is allocated when the program begins its execution. Consequently it finds another static definition after that and try to allocate memory at compile time but since its not sure of the extern declaration there is a conflict. So an error is generated as duplicate declaration.

But when the true is defined and executing the first condition, the 'a' is made static before the extern declaration and allocates the memory right at the compile time and hence further definitions doesn't conflict. I hope this helps. :)

Read this link http://www.tenouk.com/ModuleZ.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜