Reputation: 3474
The static keyword defines how a variable is to be stored in memory, i.e., in the data segment if initialized or in the BSS if uninitialized. But the keyword also specifies how a variable is to be linked, i.e., local scope only.
How or why are these two things related? Can the two be separated, or was this a necessary design consideration?
IOW, why is it that if I want my variable to exist for the duration of the program, it must be linked internally?
Upvotes: 1
Views: 191
Reputation: 30136
The keyword static
can probably be seen as somewhat "overloaded".
The following usage-options are all viable:
In terms of runtime, all types of static variables are essentially the same. They all reside in the data-section of the program, and their addresses remain constant throughout the execution of the program. So the only difference between them is during compilation, in the scope of declaration:
In terms of runtime, all types of functions (static and non-static) are essentially the same. They all reside in the code-section of the program, and their addresses remain constant throughout the execution of the program. So the only difference between them is during compilation, in the scope of declaration:
Upvotes: 1
Reputation: 145279
Re
“why is it that if I want my variable to exist for the duration of the program, it must be linked internally?”
no that is not so.
Program-global variables are supported, and that's the default for a non-const
namespace level variable. It's just wise to avoid them (to the extent possible).
Re apparent conflation of concepts in the single keyword static
, since C++ doesn't support dynamic libraries, local to the translation unit linkage is not meaningful for lifetime shorter than the program execution.
Upvotes: 1