gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

Coding > Static Variables

#8719 - Ninja - Fri Jul 18, 2003 4:49 pm

I'm trying to use a few static variables in a class that I have, yet when I go to compile, every static variable I have is listed as an undefined reference in the linking step. Am I just using them wrong, or is my makefile in error, or are they not implemented in GCC? It will compile just fine though....

I am using them sort of like this:

Code:
// .h
class Class
{
   static int Count;
   ...
};

//.cpp
Class::Count = 0;

Class::Class()
{
   ++Count;
   ...
}


Last edited by Ninja on Fri Jul 18, 2003 5:30 pm; edited 1 time in total

#8720 - Vortex - Fri Jul 18, 2003 5:05 pm

The following assignment doesn't look right:

int Class::Count = 0;

It should be Class::Count = 0;

Keep in mind there is a difference between static class members (C++ style) and static variables (C style). IMO the problem is you are trying to initialize a static class member using the C syntax for initializing static variables.

#8724 - Ninja - Fri Jul 18, 2003 5:28 pm

OOPS! That was copy and paste from someone else's example code.

I personally didn't use the int in my source code, and have edited my code to reflect that. Any other ideas?

#8729 - Ninja - Fri Jul 18, 2003 5:49 pm

Sorry... just one more thing to mention. It might be the .cpp line that's bad. How I am actually doing it in my program is by using a friend function to initialize the data.

Code:

//in .h
friend void init();

//in .cpp
void init()
{
     Class::count = 0;
}

Is there something glaringly wrong with that?

#8806 - johnny_north - Sun Jul 20, 2003 5:40 pm

What was the intended purpose of using the static? From the looks of it, you intend to do the C++ equiv. of the C #define i.e. you want to let the compiler know that a variable is garanteed not to change, this will allow the compiler to place the variable in rom rather than ram. Use static like this:

static const int KEY_A =1;

Otherwise, use static in a function definition to let the compiler know that you are declaring a variable that behaves like a global, with function scope:

void foo(){
static int x = 0; //x keeps its value over multiple call to foo()
....
}

#8850 - Ninja - Mon Jul 21, 2003 6:44 pm

What I was trying to do with the statics was to mark the index at which the current OAM memory was used up to. In this way, I can add a sprite at that index without problem. I am currently using external globals to mark the indices, but using a static would be a lot better style.

The thing that I am trying to do basically, is create a variable that's shared by all members of the class, but is not accessable outside the class. Each object created by the class should have the ability to modify the variables though.