Question

Are static variables in C++ internal variables or external variables? Or can be both?


PS: It seems to me that (not sure it's correct):

  • Internal variables are assigned their values at compile time.

  • External variables are assigned their values at link time.

Was it helpful?

Solution

Initialization depends on the type of the static variable.

  1. With fundamental types and initial values that can be computed at compile time, the variables initial value should be layed down in a section of the executable that is mapped into memory with copy on write semantics.

  2. However, the compiler can also decide to initialize static variables at runtime, typically before main() gets executed. But afaik, the only constraint is that initialization is finished when the variable is first used, and that static variables within a compilation unit are initialized in the order they are written (in case their initializers depend on one another).

The point is, that static variables are initialized before they are used by code called from main(), but it is not specified when this initialization happens. The compiler can do what it deems most efficient.

In any case, static variables live at least until main() exits or exit() is called. I am pretty sure that C++ will also call the destructors before terminating the process, but I don't know about that.

OTHER TIPS

According to the C++ Standard

3 A name having namespace scope (3.3.6) has internal linkage if it is the name of — a variable, function or function template that is explicitly declared static; or,

As for your statement that

PS: I learned that • Internal variables are assigned their values at compile time.

• External variables are assigned their values at link time.

then it is wrong.

In my opinion you are trying to mix up two notions: static storage duration and program linkage.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top