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.... 
1
  • I is possible but may not mean what you think -- I assume it has one of the other meanings of static ;-). Commented Apr 30, 2015 at 9:26

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

"as others have mentioned in their posts"... what posts?
This deprecation was undone in C++11; static on namespace scope is no longer deprecated.
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?
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. stackoverflow.com/a/6034698/440119, stackoverflow.com/a/11623473/440119
@slei yes, using extern may help you in this situation
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.