I've actually never tried it until now. Is it possible to have statics just in namespace scope without a class? Why not?
namespace MyNamespace
{
static int a;
}
assign something, somewhere else....
Annex D (Compatibility features) [C++03]
D2: The use of the static keyword is deprecated when declaring objects in namespace scope.
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.
update
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 .cpp files, the static variable becomes locally scoped to each of the .cpp files.
So now, every .cpp file that includes that header will have its own copy of that variable.
Without the static
keyword the compiler will generate only one copy of that variable, so as soon as you include the header file in multiple .cpp files the linker will complain about multiple definitions.
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