ash
ash

Reputation: 3474

why is "static" both storage class and linkage specifier?

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

Answers (2)

barak manos
barak manos

Reputation: 30136

The keyword static can probably be seen as somewhat "overloaded".

The following usage-options are all viable:

  • Static local variables
  • Static global variables
  • Static member variables
  • Static global functions
  • Static member functions

Variables:

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:

  • Static local variable: recognized by the compiler only in the scope of the function
  • Static global variable: recognized by the compiler only in the scope of the file
  • Static member variable: recognized by the compiler only in the scope of the class

Functions:

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:

  • Static global function: recognized by the compiler only in the scope of the file
  • Static member function: recognized by the compiler only in the scope of the class

Upvotes: 1

Cheers and hth. - Alf
Cheers and hth. - Alf

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

Related Questions