Static vs global

CStaticGlobal

C Problem Overview


If I have a C file like below, what is the difference between i and j?

#include <stdio.h>
#include <stdlib.h>

static int i;
int j;

int main ()
{
    //Some implementation
}

C Solutions


Solution 1 - C

i has internal linkage so you can't use the name i in other source files (strictly translation units) to refer to the same object.

j has external linkage so you can use j to refer to this object if you declare it extern in another translation unit.

Solution 2 - C

i is not visible outside the module; j is globally accessible.

That is, another module, which is linked to it, can do

extern int j;

and then be able to read and write the value in j. The same other module cannot access i, but could declare its own instance of it, even a global one—which is not visible to the first module.

Solution 3 - C

The difference is that i has internal linkage, and j has external linkage. This means you can access j from other files that you link with, whereas i is only available in the file where it is declared.

Solution 4 - C

i will have static linkage, i.e., the variable is accessible in the current file only.

j should be defined as extern, that is

extern int j;

in another header file (.h), and then it will have external linkage, and can be accessed across files.

Solution 5 - C

Scope of static variable/function is within the same file despite you include the file as part of a different source file.

Scope of global variable is throughout the files in which it is included. To include the variable in a different source file, we use extern before the variable declaration. No memory is allocated again for the variable in this case.

extern is used to declare a C variable without defining it. extern keyword extends the visibility of the C variables and C functions. Since functions are visible through out the program by default, the use of extern is not needed in function declaration/definition. Its use is redundant.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVijayView Question on Stackoverflow
Solution 1 - CCB BaileyView Answer on Stackoverflow
Solution 2 - CwallykView Answer on Stackoverflow
Solution 3 - CHans WView Answer on Stackoverflow
Solution 4 - CRamakrishnaView Answer on Stackoverflow
Solution 5 - CSravyaView Answer on Stackoverflow