Static member/function errors.

Mar 8, 2014 at 6:27pm
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();
	static int getCount() { return count; }
private:
	static int count;
};
int Test::count = 0;

#endif 


test.cpp
1
2
3
4
5
6
7
8
9
#include "test.h"

Test::Test() {
	count++;
}

Test::~Test() {
	count--;
}


main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#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";
}


Thanks for any halp!
Mar 8, 2014 at 6:44pm
Move the int Test::count = 0; on line 12 of test.h out of that file and into test.cpp.
Mar 8, 2014 at 6:49pm
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.

Thanks
Mar 8, 2014 at 6:56pm
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.
Mar 9, 2014 at 3:46am
Thanks, L B and long double main (I obviously just missed your reply before responding myself).
Topic archived. No new replies allowed.