The illusive static variable

By | September 2, 2006

Ever wondered why your static variable could have a different value assigned to it. If you are a developer in C++ and have ever used static member variables then you have run into this problem.

Well I ran into this problem quite some times. I had a static variable, which must be both declared and defined. So I did both in the header file, I know this is not a good practice but the class did not have a source file. This class was used in a lot of different source files.

I noticed a strange behaviour. Expecting the contents of the variable to be the same, it was a logging singleton, I got repeated errors that the file being written to was not open. Which made no sense to me as I did open the file and it appeared to work properly. And the log did contain the info I wrote during initialization.

So I put a favorite break point in every function using the singleton. Then came my surprise to see that the value of the pointer to the class, my static member variable, kept changing. I mean a static variable is supposed to mean that only one value can exist at one time.

On with some more debugging, this time a break point on the memory address of the static variable. Unfortunately that is the only way to figure out if it is being changed runtime. As expected I only hit it during initialization and the pointer never changed afterwards.

More mystery, how can something that does not appear to change still be different! I hadn’t got a clue as to what was going on. So I left this for a few weeks figuring a new day would somehow bring me new ideas.

And it somehow did. I was talking with another C++ developer some time later about this issue. He also had the same problem with singleton classes, specifically in templates. After a lot of debugging he found out that the pre-compiler literally copies all data from the headers a source file includes into that source file.

So if my gathering.cpp included the log.h then the declaration of the static variable would also be copied. Which means every single source file had a different declaration for the static singleton. This left my logging completely useless as every source file would have a different instance, not really the point of a singleton class!

Fixing the problem was a lot easier though. Just add a source file for the logging class with the declaration of the static variable. And after some thorough testing and debugging it worked. No more mysterious changing singletons for me! 🙂

Leave a Reply