Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding static storage class in C

Tags:

c

static is the default storage class for global variables. The two variables below (Count and Road) both have static storage class.

static int Count;
int Road;
int main()
{
    printf("%d\n", Road);
    return 0;
}

My question is: if by default global variables are static (which means we are limiting the scope of that global variable to that particular .c file) then how can we extern those variables in another file?

This question might be very basic to many of you but I am really confused and want to learn the correct details.

like image 571
user968000 Avatar asked Jun 19 '13 03:06

user968000


1 Answers

In the formal C terminology specifiers like extern, static, register etc. are called storage-class specifiers, but the actual object properties these specifiers control are called storage duration and linkage.

In your question you seem to be mixing these two unrelated concepts: storage duration and linkage. It is actually linkage that describes external visibility of the object.

All variables defined in file scope have static storage duration (regardless of whether you used the keyword static in the declaration). This simply means that they live forever, but it does not say anything about their external visibility. Meanwhile, variables defined with keyword static have internal linkage, while variables defined without any keywords or with keyword extern have external linkage.

In your example variable Road has static storage duration and external linkage, which is why you can access it directly from other translation units. Variable Count has static storage duration and internal linkage, which is why you can't access it directly from other translation units.

If you declare a variable without a storage class specifier (like Road in your example), it will be treated as so called tentative definition and finally resolve (in your example) to a variable with static storage duration and external linkage. So, from that point of view it is right to say that the default (implied) storage class specifier for file scope variables is actually extern, not static.

like image 156
AnT Avatar answered Oct 28 '22 14:10

AnT