When to use static keyword before global variables?

前端 未结 8 516
再見小時候
再見小時候 2020-11-28 20:12

Can someone explain when you\'re supposed to use the static keyword before global variables or constants defined in header files?

For example, lets say I have a head

8条回答
  •  一向
    一向 (楼主)
    2020-11-28 21:09

    static before a global variable means that this variable is not accessible from outside the compilation module where it is defined.

    E.g. imagine that you want to access a variable in another module:

    foo.c
    
    int var; // a global variable that can be accessed from another module
    // static int var; means that var is local to the module only.
    ...
    
    bar.c
    
    extern int var; // use the variable in foo.c
    ...
    

    Now if you declare var to be static you can't access it from anywhere but the module where foo.c is compiled into.

    Note, that a module is the current source file, plus all included files. i.e. you have to compile those files separately, then link them together.

提交回复
热议问题