5

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....
jeromintus
  • 367
  • 1
  • 5
  • 14

1 Answers1

4

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.

tema
  • 1,115
  • 14
  • 33
  • 1
    "as others have mentioned in their posts"... what posts? – 463035818_is_not_an_ai Apr 30 '15 at 09:22
  • 1
    This deprecation was undone in C++11; `static` on namespace scope is no longer deprecated. – Sebastian Redl Apr 30 '15 at 09:23
  • hmm i see, i have namespace with only static const data variables and would like to have this non-const static variable there too, should i change the namespace to a class? – jeromintus Apr 30 '15 at 09:43
  • If another question is similar enough that you can copy one of its answers verbatim, you should probably mark the question as a duplicate. At the very least, you need to give attribution. http://stackoverflow.com/a/6034698/440119, http://stackoverflow.com/a/11623473/440119 – Benjamin Lindley Apr 30 '15 at 09:50
  • or what if i just use extern int a; inside my namespace. this seems to work and i don't need an extra class for it – jeromintus Apr 30 '15 at 09:53
  • 1
    @slei yes, using extern may help you in this situation – tema Apr 30 '15 at 10:06