Search code examples
cstaticglobal-variables

difference between global and static variable in c


I want to know the difference between a static and a global variable. Suppose in my case below

int globvar;
static int statvariable;

int main(void)
{ }

I have defined two variables one is static and other global.Both the variables have their scope throughout the file.

So my another question is then what is the benefit of static variable in general and over global variables.


Solution

  • Both variables are "global". They both have the static storage duration. The difference is that the first has external linkage and the second has internal linkage that is it is invisible outside the compilation unit where it is declared. If the declaration of a variable with internal linkage is included in several compilation units then each of them has its own unique variable with this name.

    From the C Standard (6.2.2 Linkages of identifiers)

    2 In the set of translation units and libraries that constitutes an entire program, each declaration of a particular identifier with external linkage denotes the same object or function. Within one translation unit, each declaration of an identifier with internal linkage denotes the same object or function. Each declaration of an identifier with no linkage denotes a unique entity.

    and

    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.

    Using a variable with internal linkage hides implementation and prevents a conflict with a variable with the same name with external linkage.