views:

160

answers:

2

Hi,

What is default storage class of a global variable?

While searching on web I found, some sites say it is static. But, static means internal linkage and the variable can not be available outside the file scope i.e it should not be available to other object files. But, they still can be accessed to other files using declarations like extern int i.

And, if I explicitly mention static to global variable then it is not available outside the file scope.

Then, what is correct default storage class for the global variables?

+4  A: 

The default storage duration is static, but default linkage is external. You're not the only one to find it a bit confusing. The C Book (always a good reference) says:

"You'll probably find the interactions between these various elements to be both complex and confusing: that's because they are!"

The section with that quote, Declarations, Definitions and Accessibility, has a helpful table (8.1). The last row describes the case you're interested in. As it notes, data objects with no storage class specifier have external linkage and static duration.

Matthew Flaschen
but to have internal linkage we define global as `static int i` and if default storage class of a global variable is static then its definition would look like `static int i`, which means internal linkage.
Vinod T. Patil
As I said, the default linkage is external. The default of static only applies to duration.
Matthew Flaschen
To throw another spanner into the works: in C++, constant objects have internal linkage by default.
Mike Seymour
yes, but in C, contants have external linkage. If you define same constant in two different files, linker complains.
Vinod T. Patil
+4  A: 

There's no "default storage class" for what is commonly known as "global" variables. When a variable is defined in namespace scope it always has static storage duration. There's no way to change that, which is why the idea of something "default" is not applicable here. (And storage duration is what it is correctly called.)

When you apply the keyword static to a variable defined in namespace scope it does not affect its storage duration - it was static already and it remains static - but it affects it linkage. The keyword static changes the linkage of such variable from external (default) to internal. Linkage is a separate concept, virtually unrelated to storage duration.

AndreyT