Rationale for a static declaration followed by a non-static declaration, but not vice versa

This code will compile and is well defined according to the current C standards:

static int foo(int);
extern int foo(int);

      

The standard indicates that in this situation (C11: 6.2.2 Identifier Relationships (p4)):

For an identifier declared with an extern storage class specifier to the scope in which the provisional declaration of that identifier is visible, 31) if the previous declaration specifies an internal or external linkage, the identifier binding to the later declaration is the same as the link specified in the previous declaration ... [...]

... which means that the function int foo(int)

is declared static int foo(int)

.

Collapse these ads like this:

extern int foo(int);
static int foo(int);

      

... gives me a compiler error using GNU GCC:

the static declaration 'foo' follows the non-static declaration

My question is, what is the constructive rationale for the second case being an error and not being handled similarly to the first case? I suspect this is because the individual translation units are easier to manage and #include

? I feel like without realizing this, I might open myself to some bugs in future C projects.

+3


source to share


1 answer


I think the idea behind this confusing specification is that a declaration can be used in a function extern

to refer to a global function or object, for example to eliminate it from another identifier with the same name

static double a; // a declaration and definition

void func(void) {
  unsigned a;
  .....
  if (something) {
     extern double a; // refers to the file scope object

  }
}

      



If you are using static

, you are declaring something new:

extern double a;  // just a declaration, not a definition
                  // may reside elsewhere
void func(void) {
  unsigned a;
  .....
  if (something) {
     static double a; // declares and defines a new object

  }
}

      

+1


source







All Articles