dexterous
dexterous

Reputation: 6526

why static variable in a class gives a linking error?

Why static variable in a class has to be re-initialised as a global in the file? Otherwise, it gives a linking error. What is the theory behind it? I understand that the static variable will be in the Data Segment.

my_class.h

 class my_class
  {
  public:
  static int m_fid;
  void get_fid();
  };

my_class.cpp:

#include <iostream>
using namespace std;
int main()
{
  my_class t;
 /**this gives a linking error */ 
 my_class::m_fid = 0;
 return 0;
}

Upvotes: 2

Views: 1868

Answers (2)

HadeS
HadeS

Reputation: 2038

First of all the definition of static variable is wrong. Instead of my_class::m_fid = 0; you should define as int my_class::m_fid = 0; when you do that there will be no more linker error..

Another thing as per standard...

The definition for a static data member shall appear in a namespace
 scope enclosing the member’s class definition.

Upvotes: 5

Potatoswatter
Potatoswatter

Reputation: 137810

Yes, static variables (wherever they are declared) go into the data segment.

static means different things depending where it's used, though.

  • At file or namespace scope, it means the variable is specific to the .cpp file (translation unit).
  • At local scope, it means the variable is specific to that scope, which may be specific to the translation unit, or shared between translation units if it's in an inline function.
  • At class scope, a static member declaration inside the class is effectively (almost) the same as one outside the class with the extern specifier.

Like a variable declared extern, a static member is only considered to be declared (and not defined) until a definition is reached.

There is an exception for some static const and static constexpr members, that they may be initialized inside the class and then immediately used, subject to the restriction that the address of the member is never used.

Upvotes: 1

Related Questions