1

Possible Duplicate:
undefined reference to static member variable
What is an undefined reference/unresolved external symbol error and how do I fix it?

#include<iostream>
using namespace std;

class abc {

    private:
    static int a ;

    public:

    abc(int x) {
        a = x;
    }

    void showData() {
        cout<<"A = "<<a<<endl;
    }
};

int main() {
    abc a1(4);
    abc a2(5);

    a1.showData();
    a2.showData();

    return 0;
}

When I try to compile this function on Ubuntu with GCC compiler. I get the following error.

/tmp/ccCKK2YN.o: In function `main':
static1.cpp:(.text+0xb): undefined reference to `Something::s_nValue'
static1.cpp:(.text+0x14): undefined reference to `Something::s_nValue'
collect2: ld returned 1 exit status
Compilation failed.

Where as the following code runs fine

#include<iostream>
using namespace std;

class Something
{
public:
    static int s_nValue;
};

int Something::s_nValue = 1;

int main()
{
    Something cFirst;
    cFirst.s_nValue = 2;

    Something cSecond;
    std::cout << cSecond.s_nValue;

    return 0;
}

Is this because Static member variables needs to initialized explicitly before accessing them via objects.Why so ?

Community
  • 1
  • 1
hsinxh
  • 13
  • 4
  • http://loungecpp.wikidot.com/faq#toc4 – Seth Carnegie Oct 29 '12 at 16:26
  • See http://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix/12574407#12574407 - more specifically "static data members must be defined outside the class in a single translation unit" – Luchian Grigore Oct 29 '12 at 16:26

3 Answers3

1

static int s_nValue; doesn't allocate any storage to store the int, it just declares it.

You allocate somewhere in memory to store the variable with:

int Something::a=0;
Douglas Leeder
  • 52,368
  • 9
  • 94
  • 137
0

The declaration of a static data member in the member list of a class is not a definition. You must define the static member outside of the class declaration, in namespace scope.

See this thread.

In short, the static member needs to be initialized somewhere in a .cpp file so that the compiler allocates space for it. The declaration would look like this:

int abc::a = 0;
Community
  • 1
  • 1
Matt Kline
  • 10,149
  • 7
  • 50
  • 87
  • But I used constructor to initialize the static variable. Whats wrong with that ? – hsinxh Oct 29 '12 at 16:36
  • You can assign values to static variable in your constructor like you did, but you still need to define it in a `.cpp` file. – Matt Kline Oct 29 '12 at 16:38
0

That happens because since static members are shared between all instances of a class, they need to be declared in one single place.

If you define the static variable inside the class declaration then each include to that file would have a definition to that variable (which is against to the static meaning).

Because of that you have to define the static members in the .cpp.

Murilo Vasconcelos
  • 4,677
  • 24
  • 27