Public Group

# Static Variables In A Class - Unresolved External Symbols

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

## Recommended Posts

Hi, I'm doing a little bit of C++ programming to brush up my skills, and I'm having a spot of bother with static variables. Sample code snippet: Header
class MyClass{
private:
static int Blah;

public:
MyClass();
}

Source
MyClass::MyClass(){
int i=Blah;
//int i=MyClass::Blah;
}

I've tried the commented line as well. I believe it's implied anyway, and the compiler error is the same either way, so I think my belief is right. Either way, I'm not able to access it, and I can't see why. It doesn't make any difference if Blah is public or private. I'm getting unresolved external symbol errors from the Linker. Specifically, the symbol is "public: static int MyClass::Blah" (?Blah@MyClass@@2HA)

##### Share on other sites
You have to re-declare them also at the beginning of the source file, with simple types this is usually done to give them an initial value.

From the top of my head something like:

int CClassName::MyInt = 0;

vector CClassName::MyVector;

##### Share on other sites
Thanks man, that was exactly it.

##### Share on other sites
Perhaps it's VS doing all the work for me, but all I have to do is to include the header file in the .cpp file...

##### Share on other sites
basic types such as int can be initialised in the header where the static is declared so just do

static int Blah = 0;

no need to redeclare it in the cpp

##### Share on other sites
Quote:
 Original post by reaper93basic types such as int can be initialised in the header where the static is declared so just dostatic int Blah = 0;no need to redeclare it in the cpp

Specifically, static const integral variables only.

##### Share on other sites
Quote:
 Original post by owlYou have to re-declare them also at the beginning of the source file, with simple types this is usually done to give them an initial value.

That what's in the class declaration is the declaration, whereas that in in the source-file is called the definition.

One may also wonder why you can't write the definition in the header-file, because actually you put those include-guards "#ifndef X / #define X / #endif" in the header. While it works if the header is only included in one source-file, it won't work if multiple source files include it. This is because that static class member variable has external linkage, meaning that every source file will read/write the very same member variable. This is the reason why static members must be defined exactly once while linking.

1. 1
2. 2
3. 3
Rutin
19
4. 4
5. 5
JoeJ
12

• 13
• 21
• 9
• 31
• 16
• ### Forum Statistics

• Total Topics
632618
• Total Posts
3007467
• ### Who's Online (See full list)

There are no registered users currently online

×