Skip to main content
GameDev.net gamedev.net
🔒 Locked

How to initialize a static field in c++?

Started by Finalspace Oct 11, 2017 at 12:25 PM 4 replies 2.2k views
Original Post
Finalspace
Finalspace

I have the following code which have 4 static members in the struct. Why can i not initialize it?

I just want a bunch of predefined vectors i can use -.-


Error i get: LNK2005 "public: static union Vec2f const Vec2f::Up" (?Up@Vec2f@@@2T123@A) already defined


		union Vec2f {
			struct {
				f32 x;
				f32 y;
			};
			struct {
				f32 w;
				f32 h;
			};
			f32 elements[2];

			inline Vec2f() {
				x = y = 0;
			}
			inline Vec2f(f32 value) {
				x = y = value;
			}
			inline Vec2f(f32 newX, f32 newY) {
				x = newX;
				y = newY;
			}
			inline Vec2f(const Vec2f &from) {
				x = from.x;
				y = from.y;
			}
			
			static const Vec2f Up;
			static const Vec2f Down;
			static const Vec2f Left;
			static const Vec2f Right;
		};

		const Vec2f Vec2f::Up = Vec2f(0, 1);
		const Vec2f Vec2f::Down = Vec2f(0, -1);
		const Vec2f Vec2f::Left = Vec2f(-1, 0);
		const Vec2f Vec2f::Right = Vec2f(1, 0);


Sponji
Sponji

How about


struct Vec2f {
	union {
		struct {
			f32 x;
			f32 y;
		};
		struct {
			f32 w;
			f32 h;
		};
		f32 elements[2];
	};
  // ...


Derp
_Silence_
_Silence_

Put the initialization in the source file, not the header file.

Finalspace
Finalspace
6 minutes ago, _Silence_ said:

Put the initialization in the source file, not the header file.

There is no source file, its a math header file. But well another source file wont hurt... so putting the initialization stuff into the source file works. Thanks.

7 minutes ago, Sponji said:

How about



struct Vec2f {
	union {
		struct {
			f32 x;
			f32 y;
		};
		struct {
			f32 w;
			f32 h;
		};
		f32 elements[2];
	};
  // ...


How about what? I dont see anything at all...

Sponji
Sponji
11 minutes ago, Finalspace said:

How about what? I dont see anything at all...

1

Yeah my bad, not sure what I was thinking, dunno why it looked so weird for me having a union with constructors. Didn't notice it was a linker error.

Derp

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.