Already defined object?

I am having trouble with multiple definitions of a class within a header file. The error says:
 
  LNK2005	"public: __thiscall Shape::Shape(void)" (??0Shape@@QAE@XZ) already defined in driver.obj	


This is the header file (which is also derived into other class header files), called shape.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#pragma once
#ifndef SHAPE_H    
#define SHAPE_H  
using namespace std;

class Shape {
public:
	int posx;
	int posy;
	Shape();
	//Shape(int x, int y);
	//virtual void print();
};

Shape::Shape(){}

#endif 


And this is how it is implemented in the source file (driver.cpp).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include "shape.h"
..
other #includes with classes that are derived from shape.h
..

using namespace std;

..
function definition for addShape
..

int main()
{
	init_graphics();

	Shape *sar[50];

	addShape(sar, MAX);
	//wait 2 seconds then clear screen
	wait(2000);
	clear_screen();



	_getch();
	return 0;
}


But the code fails before it can even run, giving me only that error message. What am I doing wrong?
I was looking at some solutions and I found one you might use

Don't define Shape::Shape(){} in your header file but instead in shape.cpp

The header guards prevent a header from being included multiple times in the same translation unit, but each CPP file is (typically) a separate translation unit. So you end up with many definitions of Shape::Shape(){} - one for each CPP file where you include it (for example triangle.cpp)

from here
http://stackoverflow.com/questions/8171102/lnk2005-already-defined

I haven't tried it out but maybe this is it

Or you can try it like this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#pragma once
#ifndef SHAPE_H    
#define SHAPE_H  
using namespace std;

class Shape {
public:
	int posx;
	int posy;
	//Shape(int x, int y);
	//virtual void print();
};

#endif  
Last edited on
That did it! Thank you so much. I didn't think to try to just define it ONCE in a cpp rather than 4+ times throughout header files.
Topic archived. No new replies allowed.