Is there a use for flagging a variable as static
, when it lies in the global scope of a .cpp file, not in a function?
Can you use the static keyword for functions as well? If yes, what is their use?
Is there a use for flagging a variable as static
, when it lies in the global scope of a .cpp file, not in a function?
Can you use the static keyword for functions as well? If yes, what is their use?
In this case, keyword static means the function or variable can only be used by code in the same cpp file. The associated symbol will not be exported and won't be usable by other modules.
This is good practice to avoid name clashing in big software when you know your global functions or variables are not needed in other modules.
Taking as an example -
They both cease to exist only when the program terminates/exits.
Yes, if you want to declare file-scope variable, then
static
keyword is necessary.static
variables declared in one translation unit cannot be referred to from another translation unit.By the way, use of
static
keyword is deprecated in C++03.The section $7.3.1.1/2 from the C++ Standard (2003) reads,
C++ prefers unnamed namespace over
static
keyword. See this topic:Superiority of unnamed namespace over static?