Rationale of static declaration followed by non-static declaration allowed but not vice versa

前端 未结 2 632
囚心锁ツ
囚心锁ツ 2021-01-18 02:53

This code will compile and is well defined under current C standards:

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

The standard specifies that

2条回答
  •  無奈伤痛
    2021-01-18 03:54

    I think the idea of this confusing specification is that an extern declaration can be used inside a function to refer to a global function or object, e.g to disambiguate 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
    
      }
    }
    

    Whereas if you use static you declare 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
    
      }
    }
    

提交回复
热议问题