What is the difference between “File scope” and “program scope”

后端 未结 4 1146
南旧
南旧 2021-01-31 18:51

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:

<         


        
4条回答
  •  -上瘾入骨i
    2021-01-31 19:26

    Variables declared as static cannot be directly accessed from other files. On the contrary, non-static ones can be accessed from other files if declared as extern in those other files.

    Example:

    foo.c

    int foodata;
    static int foodata_private;
    
    void foo()
    {
        foodata = 1;
        foodata_private = 2;
    }
    

    foo.h

    void foo();
    

    main.c

    #include "foo.h"
    #include 
    
    int main()
    {
        extern int foodata; /* OK */
        extern int foodata_private; /* error, won't compile */
    
        foo();
    
        printf("%d\n", foodata); /* OK */
    
        return 0;
    }
    

    Generally, one should avoid global variables. However, in real-world applications those are often useful. It is common to move the extern int foo; declarations to a shared header file (foo.h in the example).

提交回复
热议问题