What am I doing wrong with static members and methods here?
compiler errors:
1>test.obj : error LNK2005: "private: static int Test::count" (?count@Test@@0HA) already defined in main.obj
1>c:\users\james\documents\visual studio 2013\Projects\static_test\Release\static_test.exe : fatal error LNK1169: one or more multiply defined symbols found
test.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#ifndef TEST_H_
#define TEST_H_
class Test {
public:
Test();
~Test();
staticint getCount() { return count; }
private:
staticint count;
};
int Test::count = 0;
#endif
#include <iostream>
#include "test.h"
using std::cout;
void newTest();
int main() {
Test test1;
Test test2;
cout << Test::getCount() << " Test objects exist before function call\n";
newTest();
cout << Test::getCount() << " Test objects exist after function call\n";
system("pause");
return 0;
}
void newTest() {
Test newTest;
cout << Test::getCount() << " Test objects exist inside function call\n";
}
Well, I figured out the problem after toying with it. The code runs fine if I move the static member definition to the class implementation file (test.cpp), instead of it existing inside the header file.
int Test::count = 0;
Can someone explain why this is the case? I thought the #ifndef / #define / #endif statements would have kept anything they contained from being defined more than once.
Include guards prevent multiple definition in the same translation unit. They do not prevent multiple definition across the whole program.
A function or class can be declared as many times as you like throughout a program as long as all the declarations are the same, however there must always be exactly one definition.
Since a header file gets included in multiple files, you have the potential to create multiple definitions.