I\'ve seen the word static
used in different places in C code; is this like a static function/class in C# (where the implementation is shared across objects)?
Static variables in C have the lifetime of the program.
If defined in a function, they have local scope, i.e. they can be accessed only inside those functions. The value of static variables is preserved between function calls.
For example:
void function()
{
static int var = 1;
var++;
printf("%d", var);
}
int main()
{
function(); // Call 1
function(); // Call 2
}
In the above program, var
is stored in the data segment. Its lifetime is the whole C program.
After function call 1, var
becomes 2. After function call 2, var
becomes 3.
The value of var
is not destroyed between functions calls.
If var
had between non static and local variable, it would be stored in the stack segment in the C program. Since the stack frame of the function is destroyed after the function returns, the value of var
is also destroyed.
Initialized static variables are stored in the data segment of the C program whereas uninitialized ones are stored in the BSS segment.
Another information about static: If a variable is global and static, it has the life time of the C program, but it has file scope. It is visible only in that file.
To try this:
static int x;
int main()
{
printf("Accessing in same file%d", x):
}
extern int x;
func()
{
printf("accessing in different file %d",x); // Not allowed, x has the file scope of file1.c
}
run gcc -c file1.c
gcc -c file2.c
Now try to link them using:
gcc -o output file1.o file2.o
It would give a linker error as x has the file scope of file1.c and the linker would not be able to resolve the reference to variable x used in file2.c.
References: