Search code examples
c++linkage

why do " int ClassName :: VariableName " always needed to complete linkage?


  class X {
       static int i;
       // some other function, variable declaration, cons, dest
  };

  int X :: i ; **(!)** 

Why must I write that (!) line, always ?

If I dont write, compiler cannot complete internal linkage, and so it gives ( I assume ) linker error. Why ?


Solution

  • This is known as the One Definition Rule. Each global object (technically, each object with external linkage) must be defined in exactly one source file (technically, in one translation unit). However, it can be declared as many times as you like.

    Typically, a class definition will be in a header file, which might be included by many source files. So any static members can't be defined there, only declared, otherwise there will be multiple definitions. You must separately define the static members in exactly one source file, in order for the linker to find exactly one definition. That is what the line marked (!) does.