Static Variable Value Reverts

Started by
1 comment, last by X Abstract X 13 years, 9 months ago
I'm really confused about why this isn't working the way I expect. I know I'm not doing something right but, what exactly is happening and how can I fix this?

Foo.h
#ifndef Foo_h#define Foo_hstatic int bar = 10;void modifyBar();#endif



Foo.cpp
#include "Foo.h"void modifyBar() {    bar = 20;}


When I print out bar after calling modifyBar(), I get a value of 10, expecting to get 20. I did a bit of testing and I'm thinking it has something to do with splitting up the code into 2 separate files?
Advertisement
static int bar = 10;

This means, make a global variable named bar, which is only visible from this CPP file. Seeing you've got that in the header, you've actually got one bar member per CPP file that includes that header. modifyBar is only changing one of your bar variables.


You probably want this:
//headerextern int bar;void modifyBar();//CPPint bar = 10;void modifyBar() {    bar = 20;}
..which will only make one bar variable that any CPP file can access.
Thanks. Makes perfect sense now.

This topic is closed to new replies.

Advertisement