C++ static variables

I'm working on a project in C++ and I created a static member function and a static data member in one of my classes. When I tried to compile I kept getting an unresolved external error that was pointing to my static data member and I couldn't figure out what the problem was. Finally after some research (via Google, Msdn, and Stroustrup) I figured out that you have to define the static data member outside the class declaration.

I don't consider myself to be a novice C++ programmer but I don't think I ever knew this rule. Am I the only one who didn't know this? I guess for the most part I don't use static member variables very much, I know I have used local function static variables and static functions but I guess I have never used a static data member because I know I would have remembered this rule. At any rate I know now and knowing is half the battle ;)

Here is a small code snippet to show what needs to be done:

  1 // MyClass.h
  2 class MyClass
  3 {
  4 public:
  5 	static int GetCount() { return count; }
  6 private:
  7 	static int count;
  8 };

  1 // MyClass.cpp
  2 #include "MyClass.h"
  3 int MyClass::count; // Also do any initialization if needed.

52 Comments

  • You need to declare it outside the class because otherwise the compiler doesn't know which translation unit (hence object file) the member is supposed to go.



    One of the drawbacks of C++'s rather archaic compilation model.

  • I never knew that either. I use static variables and functions every day in C, but of course I never do C++ anymore. I'll have to remember this one.

  • Right. I was exactly searching after this. Because: hat the same problem. And I called me already a C++ expert. But you never run out of gotchas with c++. Or who knows about the explicit keyword

  • It gives a linking error and you keep guessing why this is not working.You have to make the static variable declared outside the class.

  • Here's an interesting question then:

    At what point will those static variables' memory get cleaned up? When the process exits?

  • put a breakpoint in a destructor and see

  • I totally forgot about this rule. I spent a half day trying to rid my program of the 'unresolved external ...' errors. Thanks for the posting.

  • Static data members must be defined out side of class definition, because they don't belong to any specific instance of the class.

  • Static member functions get defined in the class and so should static member variables. Looks like a hack related to compilers when they made this, probably some esoteric reason for it.

  • I just encountered this problem (and the solution).

    I've concluded that this problem is due to

    o the C++ separation of definitions (in .h files), and declarations (in .c files).
    o a runtime data model that doesn't necessarily include a "class object".

    For contrasting treatment, take a look at java.

  • This was a great post. I had the same problem when I tried to implement a Singleton in C++ but the unresolved reference to the static data kept tripping me up. Now I know what to do thanks to you.

  • thx for the posting, save my prroblem, now!!

  • C programmers, think of "extern" -- you're just publishing the linkable location of a global.

  • Seems you are in good company ;) So many people who don't know that one and, oh, of course that was the reason why I stumbled across your blog. Didn't knew it either ^^

  • Hi,
    Thanks a lot!!
    I spent half a day tring to solve this problem.

  • in this code you dont need the variable definition in the header file, only in the cpp file, try this code without the static definition in the header, it works the same...

    so i think its not the way how static members should be used, because its not a static and not a member, its a simple global variable...

  • yeah, so, you saved my night, etc, etc.

  • I've been banging my head on the desk all morning - but your post has saved me!!

  • Thanks a lot ! I spent the whole day trying to figure why i was getting the unresolved symbols

  • //statictest.h
    class
    statictest
    {
    public:
    static int a;
    void sum();
    };
    ///////////////////////////////////////////////

    //statictest.cpp
    #include "statictest.h"

    int statictest::a; //Pay attention

    void statictest::sum(){
    a=0;
    }
    ///////////////////////////////////////////////

    //main.cpp
    #include "statictest.h"
    int main()
    {
    statictest test;
    test.sum();
    }
    ///////////////////////////////////////////////




  • Thanks a lot... !!!

  • REASON :: Class definition is just a template. No memory is allocated. But static variable requires memory allocation unlike other data members who will get their memory from instance definition.
    Hence, static data members have to be "Defined" seperately.

  • The last one was precise...thanks!!!!

  • finally some one explains this .....

  • Thanks a lot! I spent some time trying to find the reason behind my "static" errors. Now, it is clear.

  • Well, I just found out on this page. Anyway - thank you.

  • hey can somebody throw light on this :

    after declaring the static variables inside and outside ( for memory allocation) the class
    using the :: , is the static variable still a member of the class ?

    if it is then why its size does not show up if we say sizeof(object) of the class?

  • "size does not show up if we say sizeof(object) of the class?"

    It is not part of the allocated memory when an object is created, otherwise it would not make sense, as that would mean a new static member would have space for each object creation. This all stays consistent for memory allocations using malloc(sizeof(Class)) etc, as sizeof should not return the size of the class, but the size of an object to created. (As far as I know anyhow).

    I think static members are simply a global variable that is resolved in the name space of the class (e.g. Class::static_var)

  • Gracias a Ansari-Keshtkaran por regalarme la
    solución al problema que me hizo qudar despierto
    toda una noche. Mil gracias...

  • This was really helpful! I had the same problem in using the static variable and implementing singleton pattern.

    Thanks for the info and have a nice holidays !

    -SV

  • Many thanks!!!!!!!!!!!

    The problem that I had was that it was vital to put the line

    int MyClass::count;

    into the .cpp file and NOT in the .h file

    this made that clear.

  • Yup, this is the retarded nature of C++.

    It doesn't have "true" class variables - just global variables that, with some hand waving and judicious squinting, we PRETEND are class variables.

    Objective C has true class variables. Which requires less headbanging and better production of code.

    But who uses Objective C other than Apple?

  • Many thanks!!!!!!!!!!

  • Thanks...I seem to recall this now, but I still beat my head on it most of the day!!!!!

  • Awesome didn't know that and it fixed my bug!

    Thanks!

  • Yeah..in Java this is a common practice to have static member variables. I was totally confused today when trying to brush up on some C++ programming and getting this error! hehehe...

  • I am using static variables in c++ code and have a linking to be done as the code is developed as a library.When linking I get the error as undefined reference to these variables.

    .h
    MyClass
    {
    static int var;
    }

    .cc

    MyClass::var = 0;//initializing.

    MyClass::Add_Entry()

    {
    if(var == 0)
    {
    //get no: of entries(int)
    var = var + entries;
    }
    else
    {
    for(var =0;var < MAX_ENTRIES;var ++)
    {
    //do something
    }
    }

    }

    This code compiles fine with the above definition in the .cc file.However it shows error in linking with the error :Undefined Reference to var.

    Can anyone help me here?

  • You should also put data type before the line of initialization, which should look like this.

    int MyClass::var = 0;

    Because it's not "initialization", it's actually defining that variable.

  • I learned this in C++ 101. The aggravating thing is that it is really extern data, so you can't protect it from being accessed.

    If you can, use function static data instead, that is, if it's a table, put it in a method that does nothing but handle the access to it, by which I don't mean a getter method but a method to interpret it. Or use (ugh) file static and put all of the implementations that use it in the same source file.

    OK now, how do I get a static const table to be generated at compile time? It does use classes, but these do not reference any run-time data and could be expressed as old-fashioned C initializations except that the table does use the STL string class.

  • Better define static member functions outside the class. Some compilers(IBM) don't allow this to be inlined & creates separate static copy of the function in all the translation units that include this header. So, if you further define a static variable inside that static function ( e.g. Singleton definition ) you are going to face trouble because different translation units will have different function-static objects, which you really do not want.

  • Thanks. I was having the same problem. Feel kinda silly about it though xD

  • but y dont i need to define the same static variable globally in C?

  • Thanks, that was very instructive!

  • This was extremely uselful, thanks!!

  • Thank a lot...!!!

    Its solved my problem as well..

  • Can anyone help with local static variables?

  • Thanks for the help..saved my day

  • Thanks! I've been popping veins trying to figure this out. I'm not *exactly* a C++ expert (I'm a mathematician who prefers Python), but this is typical of why I'm not pleased to have to deal with C++ right now!

    (It would be a lot nicer if C++ would just behave in more intuitive ways...)

  • Man!!!

    You rock...it was awesome. I swear I had tried everything to solve the external link error. And I haven't another option ...

    You're great!

    thanks!

  • Thanks it helped a lot!!

  • Thankyou thankyou!

    I was stuck on this for a while.
    This post is still very relevant (especially newcomers to c++ like me)

  • ah - found the answer to the constructor destructor issue with class counts -- the copy-constructor has to increment the count as well
    So it was a 'beginner' issue

Comments have been disabled for this content.