On local and global static variables in C++

The differences are:

  • The name is only accessible within the function, and has no linkage.
  • It is initialised the first time execution reaches the definition, not necessarily during the program’s initialisation phases.

The second difference can be useful to avoid the static intialisation order fiasco, where global variables can be accessed before they’re initialised. By replacing the global variable with a function that returns a reference to a local static variable, you can guarantee that it’s initialised before anything accesses it. (However, there’s still no guarantee that it won’t be destroyed before anything finishes accessing it; you still need to take great care if you think you need a globally-accessible variable. See the comments for a link to help in that situation.)

Leave a Comment