I know this question has already been asked, but googling around I didn't find a real answer to it. What I mean is: static member functions (and also non-static ones, for that matter) can be defined in their class at the same time that they are declared. Why cannot this be done for static member variables? It would not break the one definition rule. Is this specified in the standard? If yes, what is the reason behind it?
Asked
Active
Viewed 1,765 times
2
-
http://programmers.stackexchange.com/questions/145299/why-the-static-data-members-have-to-be-defined-outside-the-class-separately-in-c – Mat May 27 '14 at 12:53
-
1Yes, it **could** break the one-definition rule. Imagine a class declaration that defines static variable in `.h` that is included by 2 `.cpp` files. Bang, you just defined it twice, once fore each '.cpp'. A way was needed to make the static a declaration, so it was made a declaration by default (as it's for the best in most cases). – Agent_L May 27 '14 at 12:55
-
@agent_l You can have a function definition appear in multiple translation units if it is `inline` though. The OP is asking why you cannot do this for static member variables. – JBentley May 27 '14 at 13:04
-
1@JBentley I understood this as "written-in-line", not actual `inline` keyword. `inline` means that this piece of code may be duplicated and created a new instance in place. What makes absolutely no sense for variable, as the whole point of variable is to share one value across all accesses. – Agent_L May 27 '14 at 13:10
1 Answers
2
When you write this:
struct A
{
static int a; //class scope
}
static int b; //namespace scope - static makes b to have internal linkage!
Here, a
has external linkage despite being declared static
which in the other case makes b
to have internal linkage. If you want the definition of a
to be inlined (like the member functions), then it has to have internal linkage otherwise inclusion of the header in multiple cpp file would result in multiple-redefinition error. Also the internal linkage entirely changes the scope of the variable — every translation unit will have its own instance of the variable a
, i.e there wouldn't be one single value of a
in all translation unit.

Nawaz
- 353,942
- 115
- 666
- 851