PDA

View Full Version : C++ Static Functions



weaver4
16th November 2009, 22:43
This may be the stupidest question ever asked on this forum but I have the following code.

#Header File


#ifndef GSETTINGS_H
#define GSETTINGS_H

#include <QObject>
#include <QSettings>
#include <QString>
#include <QPointer>

class gSettings : public QObject
{
private:
public:
gSettings();
static bool OpenSettings(QString filename);
static int i;
};

#endif // GSETTINGS_H


# here is the implementation


#include "gsettings.h"
#include <QSettings>

gSettings::gSettings()
{
}

bool gSettings::OpenSettings(QString filename)
{
i = 12;
return true;
}


And I get the following error on the line "i=12"

/home/weavert/Development/QT-Projects/Settings/Settings/gsettings.cpp:10: undefined reference to `gSettings::i'

What am I doing wrong.?

wysota
16th November 2009, 22:54
You need to initialize every static variable (gSettings::i in your case). Add this to your implementation code outside any method body (i.e. right beneath include statements):

int gSettings::i = 0; // you can skip the "= 0" part if you like random values

squidge
16th November 2009, 22:56
Don't know. Broken compiler? It obviously knows the context as it's quoted it, but don't know why it says its undefined.

The kind of code you've written will work fine on some compilers.

calhal
16th November 2009, 23:04
Don't know. Broken compiler?
It's not. Read what wysota wrote above.

weaver4
17th November 2009, 01:21
Thanks so much!! That fixed it.

That was not in my C++ book(s).

squidge
17th November 2009, 08:43
It's not. Read what wysota wrote above.

Strange, I just copied and pasted the code and it works fine here. Maybe it's my compiler thats broken :o

calhal
17th November 2009, 09:07
From Thinking in C++


Because static data has a single piece of storage regardless of how many objects are created, that storage must be defined in a single place. The compiler will not allocate storage for you. The linker will report an error if a static data member is declared but not defined.

The definition must occur outside the class (no inlining is allowed), and only one definition is allowed. Thus, it is common to put it in the implementation file for the class. The syntax sometimes gives people trouble, but it is actually quite logical. For example, if you create a static data member inside a class like this:

class A {
static int i;
public:
//...
};
Then you must define storage for that static data member in the definition file like this:

int A::i = 1;

squidge
17th November 2009, 10:42
Yes, It makes sense, I'm just wondering why my compiler doesn't require it.

And now I know why - it was optimising it out. If I do some more work with it, such as assign it to a volatile or such like, then it quite happily throws up a linker error.

You may have noticed I've never used a c++ static member variable. Static functions a plenty, but never variables.