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;
}
Community
  • 1
  • 1
  • 1
    you should change return of `init` to void, or return something – Karthik T Jan 15 '13 at 05:09
  • 3
    This question has been asked countless times before: http://stackoverflow.com/questions/272900/c-undefined-reference-to-static-class-member http://stackoverflow.com/questions/12117859/c-undefined-reference-to-static-variable http://stackoverflow.com/questions/3672088/undefined-reference-error-due-to-use-of-static-variables http://stackoverflow.com/questions/7787059/g-undefined-reference-static-member-variable and many more – Adam Rosenfield Jan 15 '13 at 05:11

2 Answers2

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.

billz
  • 44,644
  • 9
  • 83
  • 100
  • 2
    What if it is private? Can you still access it to define it? – Goodies Dec 28 '15 at 09:38
  • @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: https://stackoverflow.com/questions/14331469/undefined-reference-to-static-variable#comment19917983_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. – Chris Tophski Jun 27 '19 at 15:56
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;
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198