Search code examples
cscopestorage-class-specifier

What is the difference between "File scope" and "program scope"


A variable declared globally is said to having program scope
A variable declared globally with static keyword is said to have file scope.

For example:

int x = 0;             // **program scope**   
static int y = 0;      // **file scope**  
static float z = 0.0;  // **file scope** 

int main()  
{  
   int i;   /* block scope */  
   /* .
      .
      .
   */ 
   return 0;  
}  

What is the difference between these two?


Solution

  • In C99, there's nothing called "program scope". In your example variable x has a file scope which terminates at the end of translation unit. Variables y and z which are declared static also have the file scope but with internal linkage.

    C99 (6.2.2/3) If the declaration of a file scope identifier for an object or a function contains the storage class specifier static, the identifier has internal linkage

    Also, the variable x has an external linkage which means the name x can is accessible to other translation units or throughout the program.

    C99 (6.2.2/5) If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.