namespace N { static int x = 5; }
What could be the importance/use-cases of declaring having a static variable at namespace scope?
Unnamed Namespaces Also see Static Variables. All declarations can be given internal linkage by placing them in unnamed namespaces, and functions and variables can be given internal linkage by declaring them static . This means that anything you're declaring can not be accessed from another file.
When you declare a variable as static , it means that its scope is limited to the given translation unit only. Without static the scope is global. When you declare a variable as static inside a . h file (within or without namespace ; doesn't matter), and include that header file in various .
1.1 Unnamed namespaces, paragraph 2: The use of the static keyword is deprecated when declaring objects in a namespace scope, the unnamed-namespace provides a superior alternative. Static only applies to names of objects, functions, and anonymous unions, not to type declarations.
A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.
static
variable at namespace scope (global or otherwise) has internal linkage. That means, it cannot be accessed from other translation units. It is internal to the translation unit in which it is declared.
Annex D (Compatibility features) [C++03]
D2: The use of the static keyword is deprecated when declaring objects in namespace scope.
Use unnamed namespaces instead as mentioned in this post.
static keyword imparts internal linkage to variables/objects in C as well as in C++ in namespace scope as others have mentioned in their posts.
P.S: Thie feature has been undeprecated as per the latest draft (n3290). In n3225 §7.3.1.1/2
is present but striked out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With