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.
Published Friday, November 05, 2004 12:51 AM by puzzlehacker

Comments

# re: C++ static variables

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.

Friday, November 05, 2004 1:39 AM by Dean Harding

# re: C++ static variables

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.

Friday, November 05, 2004 9:07 AM by Joe Payne

# re: C++ static variables

That has always bugged me. I get around it with something like this:
static int GetCount()
{
static int count = 0;
return count;
}

This also helps to get around some "order of initialization" issues across statics. i.e. if one static initialization depends on another static.

Friday, November 05, 2004 11:32 AM by Dave Montgomery

# re: C++ static variables

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

Monday, August 07, 2006 7:00 PM by Rob

# re: C++ static variables

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.

Wednesday, August 16, 2006 1:55 AM by Nikhil

# re: C++ static variables

Here's an interesting question then: At what point will those static variables' memory get cleaned up? When the process exits?

Tuesday, August 22, 2006 2:28 PM by Marco Casalaina

# re: C++ static variables

put a breakpoint in a destructor and see

Friday, August 25, 2006 1:01 AM by aadad

# re: C++ static variables

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.

Tuesday, August 29, 2006 1:21 PM by Doug Menifee

# re: C++ static variables

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

Wednesday, October 25, 2006 8:55 PM by Anil

# re: C++ static variables

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.

Saturday, October 28, 2006 12:31 PM by Bruce

# re: C++ static variables

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.

Wednesday, November 08, 2006 9:58 AM by bill schauweker

# re: C++ static variables

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.

Friday, December 08, 2006 9:07 PM by Angelo Rohit

# re: C++ static variables

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

Monday, February 05, 2007 10:41 AM by FRank

# re: C++ static variables

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

Wednesday, February 07, 2007 3:21 PM by Bluejack

# re: C++ static variables

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 ^^

Thursday, February 08, 2007 5:39 AM by 3Peso

# re: C++ static variables

Hi,

Thanks a lot!!

I spent half a day tring to solve this problem.

Monday, February 12, 2007 3:44 AM by Lior

# re: C++ static variables

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...

Wednesday, February 14, 2007 9:21 AM by peter

# re: C++ static variables

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

Wednesday, February 21, 2007 9:45 PM by cb

# re: C++ static variables

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

Saturday, February 24, 2007 8:25 PM by Russell

# re: C++ static variables

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

Tuesday, March 06, 2007 7:21 PM by Harshal

# re: C++ static variables

//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();

}

///////////////////////////////////////////////

Friday, March 09, 2007 4:58 AM by Ansari-Keshtkaran

# re: C++ static variables

Thanks a lot... !!!

Sunday, April 08, 2007 8:17 PM by miya

# re: C++ static variables

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.

Monday, April 23, 2007 9:57 AM by makarand kokane

# re: C++ static variables

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

Friday, July 13, 2007 11:34 PM by gs

# re: C++ static variables

finally some one explains this .....

Friday, August 03, 2007 1:45 PM by sam

# re: C++ static variables

hehe, thanks alot for this, was working all last night on it and couldn't see any way except to make it a normal member, which of course I wouldn't need.

Monday, August 06, 2007 5:48 PM by Steven

# re: C++ static variables

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

Friday, August 10, 2007 9:59 AM by jbazzo

# re: C++ static variables

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

Friday, August 17, 2007 8:07 AM by Alessandro

# re: C++ static variables

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?

Wednesday, October 10, 2007 9:25 AM by Prasad

# re: C++ static variables

"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)

Wednesday, November 21, 2007 12:55 AM by Kyle

# re: C++ static variables

Gracias a Ansari-Keshtkaran por regalarme la

solución al problema que me hizo qudar despierto

toda una noche. Mil gracias...

Monday, December 10, 2007 5:43 PM by Oscar Palacios

# re: C++ static variables

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

Saturday, December 15, 2007 7:02 PM by sv

# re: C++ static variables

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.

Monday, February 11, 2008 7:20 AM by AlanE

# re: C++ static variables

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?

Wednesday, April 16, 2008 10:39 AM by feloneouscat

# re: C++ static variables

Many thanks!!!!!!!!!!

Friday, May 23, 2008 12:39 AM by Dev

# re: C++ static variables

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

Wednesday, July 09, 2008 5:20 PM by DAWorX

# re: C++ static variables

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

Thanks!

Thursday, August 07, 2008 11:44 AM by AWR

# re: C++ static variables

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...

Monday, August 18, 2008 3:09 PM by Juice

# re: C++ static variables

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?

Wednesday, August 20, 2008 7:15 AM by VR

# re: C++ static variables

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.

Friday, September 12, 2008 4:45 PM by W2

# re: C++ static variables

Thanks i have been struggling from last 3 hours......thanks u posted it

Saturday, October 04, 2008 6:40 PM by Deependu

# re: C++ static variables

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.

Sunday, November 23, 2008 12:22 AM by Michael

# Class declarations and definitions &laquo; :maohao:

Pingback from  Class declarations and definitions &laquo; :maohao:

Sunday, December 14, 2008 8:10 PM by Class declarations and definitions « :maohao:

# re: C++ static variables

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.

Thursday, January 01, 2009 12:48 AM by Subhra

# re: C++ static variables

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

Monday, March 02, 2009 6:41 PM by Всеволод

# re: C++ static variables

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

Tuesday, April 07, 2009 4:55 AM by ankita

# re: C++ static variables

Thanks, that was very instructive!

Monday, April 20, 2009 4:52 PM by Terracotta-Fin

# re: C++ static variables

This was extremely uselful, thanks!!

Monday, May 04, 2009 11:25 PM by Cauvery

# re: C++ static variables

Thank a lot...!!!

Its solved my problem as well..

Wednesday, May 20, 2009 10:18 AM by Jitesh

# re: C++ static variables

Can anyone help with local static variables?

Sunday, May 31, 2009 2:04 AM by honey

# re: C++ static variables

Thanks for the help..saved my day

Thursday, August 20, 2009 9:58 PM by Vaibhav

# re: C++ static variables

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...)

Thursday, September 03, 2009 2:07 PM by Alpheus

# re: C++ static variables

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!

Wednesday, October 21, 2009 8:38 PM by Jacare Brasil

# re: C++ static variables

Thanks it helped a lot!!

Monday, November 02, 2009 5:27 PM by DK

# re: C++ static variables

Thankyou thankyou!

I was stuck on this for a while.

This post is still very relevant (especially newcomers to c++ like me)

Saturday, December 05, 2009 6:27 PM by Steven B

Leave a Comment

(required) 
(required) 
(optional)
(required)