Search code examples
cstaticextern

Static variables and extern in plain C


Is there a difference between declaring a static variable outside of a function and declaring a static variable inside a function?

Also, what's the difference between declaring a variable as static and just declaring an extern variable?


Solution

  • The difference is that the static variable inside the function is visible inside the function only, whereas the static variable outside may be seen by any function from its point of declaration to the end of the translation unit.

    Otherwise, they behave the same.

    Declaring a variable outside of a function without the keyword static means it is visible (accessible) outside the file (translation unit) where it is defined (as well as from the point of definition to the end of the translation unit). If you declare a variable as extern, it means that there is a definition somewhere else - possibly in the same translation unit, but more likely in another. Note that it is possible to declare an extern variable inside a function, but it can only be defined outside of a function.