32

Possible Duplicate:
C++: undefined reference to static class member

I'm using MinGW. Why static variable is not working

[Linker error] undefined reference to `A::i' 

#include <windows.h>

    class A { 
        public:     
        static int i;
        static int init(){

            i = 1;  

        }

    };

int WINAPI WinMain (HINSTANCE hThisInstance,
                    HINSTANCE hPrevInstance,
                    LPSTR lpszArgument,
                    int nFunsterStil){
    A::i = 0;
    A::init();

    return 0;
}
2

2 Answers 2

48

You only declared A::i, need to define A::i before using it.

class A  
{ 
public:     
  static int i;
  static void init(){
     i = 1;  
  }
 };

int A::i = 0;

int WINAPI WinMain (HINSTANCE hThisInstance,
                HINSTANCE hPrevInstance,
                LPSTR lpszArgument,
                int nFunsterStil)
{
  A::i = 0;
  A::init();

  return 0;
}

Also your init() function should return a value or set to void.

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

2 Comments

What if it is private? Can you still access it to define it?
@Goodies I had no problem with a private static member in my test. Though I needed a hint from the first link of this comment: stackoverflow.com/questions/14331469/… of this question. I think this seemed to be the problem with private members in your case. If it's a structural problem with member visibility in the class definition and you need a certain member declaration order, you may also have multiple private/public/protected blocks (each with one or more members) in sequence.
19

You have declared A::i inside your class, but you haven't defined it. You must add a definition after class A

class A {
public:
    static int i;
    ...
};

int A::i;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.