So depending upon the scope of the variable does static key word has different meaning?
Then is my following understanding correct ?
1) If it is associated with a variable inside function
i.e the variable has automatic storage duration as below
foo() {
int x;
}
The static provide the variable x static storage duration but it does notprovide any linkage to x.
2) If it is associated with a variable outside function that has externallinkage
/*file.c/
int x
The keyword static here does not provide static storage duration as the variable x already has static storage duration. Here it provides internal linkage.
So in essence static mainly provide static storage duration who needs it but it provide local linkage who has already static storage duration.
Why C has different meaning for same keyword? is it for minimizing the number of keyword ?
Also I do not have a very clear distinction between internal linkage andno linkage.
According to my understanding linkage is a way to identify the connection between identifiers in separate file .
If the situation is as follows
1.c
+++++
#include<stdio.h>
int i;
int main(void)
{
printf("\n value of i = %d\n",i);
return 0;
}
+++++++
2.c
int i =5;
+++++
Now if these two files are compiled and linked the output will be
value of i = 5
So in this case in file 1.c i has the external linkage and which refer to the same i defined in 2.c
Now if I change 1.c as follows
#include<stdio.h>
static int i;
int main(void)
{
printf("\n value of i = %d\n",i);
return 0;
}
the output is
value of i = 0
Here i has internal linkage and also by default in C static variable is initialized so i is initialized to 0 .
Now if I change 1.c as follows
#include<stdio.h>
int main(void)
{
static int i;
printf("\n value of i = %d\n",i);
return 0;
}
Now i has no linkage and initializes to 0. So the output is
value of i = 0
So the output is same for the case of internal and no linkage. My question is what is the significance of internal linkage ? Is it a way of saying that in a particular file if an identifier has internal linkage then that identifier only can be referred in that file . If the identifier has no linkage then if the identifier goes out of scope it can no longer be referred.
So for example
#include<stdio.h>
static int i =15;
int main(void)
{
extern int i;
printf("\n value of i = %d\n",i);
return 0;
}
Here i has internal linkage but it can be referred from the same file. extern int i; is referring to static int i =15;
So here the output will be
value of i = 15
Now in the following case
#include<stdio.h>
static int i =15;
void foo()
{
int x =20;
}
int main(void)
{
extern int i;
printf("\n value of i = %d\n",i);
return 0;
}
i has no linkage in foo() so there is no way it can be referred to from outside foo() . So extern int i; refer to static int i =15; only.
So if this is only difference between no linkage and internal linkage?