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.

  • const and static 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.

Anonymous namepsaces

Use to declare many things with internal linkage.

namespace {
int a = 0;
int b = 0;
int c = 0;

See linkage.

results matching ""

    No results matching ""