tags:

views:

125

answers:

4
+1  Q: 

Static vs global

if i have a c file like below

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

static int i;
int j;

int main ()
{
//some implementation
}

What is the difference between i & j?

+1  A: 

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.

wallyk
Is the 'extern' declaration necessary?
Thomas Matthews
It depends on the implementation. Use of `extern` is guaranteed to not cause trouble, provided one module has the symbol as non-`extern` and public (which allocates it). Early Unix implementations merged symbols with the same name—much like a Fortran common—so `extern` was not required.
wallyk
+1  A: 

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.

Hans W
+1  A: 

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.

Charles Bailey
A: 

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

The variable j should be defined as extern (extern int j) in one of the header files and then it will have external linkage and can be acessed across files.

Ramakrishna