Use of static in C++
Dependencies on static variables in different translation units are, in general, a code smell and should be a reason for refactoring. http://www.modernescpp.com/index.php/c-20-static-initialization-order-fiasco
const
andstatic
variables don't have external linkage; non-const global variables have external linkage by default; const global variables have internal linkage by default- Variables with static storage duration are zero initialised. According to the standard: "All objects which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration".
- Functions have external linkage by default
If an object or function inside such a translation unit has internal linkage, then that specific symbol is only visible to the linker within that translation unit. If an object or function has external linkage, the linker can also see it when processing other translation units. The static keyword, when used in the global namespace, forces a symbol to have internal linkage. The extern keyword results in a symbol having external linkage.
- Always use auto
- Dynamic Storage Duration
Automatic Storage Duration
What’s the “static initialization order ‘fiasco’ (problem)”?
- C++ scoped static initialization is not thread-safe, on purpose! (pre-C++11)
- constinit
- static vs std::call_once vs double checked locking
- Double-Checked Locking Pattern
Anonymous namepsaces
Use to declare many things with internal linkage.
namespace {
int a = 0;
int b = 0;
int c = 0;
}
See linkage.