declare extern variable within a C function?

Wang Tuma picture Wang Tuma · Aug 20, 2013 · Viewed 9.4k times · Source

I define a variable in a C file: int x, and I know I should use extern int x to declare it in other files if I want to use it in other files.

My question is: where should I declare it in other files?

  1. Outside of all functions,

    // in file a.c:
    int x;
    
    // in file b.c:
    extern int x;
    void foo() { printf("%d\n", x); }
    
  2. within the function(s) that will use it?

    // in file b.c:
    void foo() {
       extern int x;
       printf("%d\n", x);
    }
    

My doubts are:

  • Which one is correct?, or
  • Which is preferred if both are correct?

Answer

Lidong Guo picture Lidong Guo · Aug 20, 2013
  1. Both are correct.

  2. Which one is preferred depend on the scope of variable's use.

    • If you only use it in one function, then declare it in the function.

      void foo() 
      {
           extern int x;   <--only used in this function.
           printf("%d",x);   
      }
      
    • If it is used by more than one function in file, declare it as a global value.

      extern int x;   <-- used in more than one function in this file
      void foo()
      {
          printf("in func1 :%d",x);   
      }    
      void foo1() 
      {
          printf("in func2 :%d",x);   
      }