Jump to content
  • Advertisement
Sign in to follow this  
X Abstract X

Static Variable Value Reverts

This topic is 2907 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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_h

static 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?

Share this post


Link to post
Share on other sites
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:
//header
extern int bar;
void modifyBar();

//CPP
int bar = 10;
void modifyBar() {
bar = 20;
}
..which will only make one bar variable that any CPP file can access.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!