can't access a static private field from static method

Hello,

I was making a bit code to let me throw fatal errors, that get logged and make my Sketch stop running (as a substitute for the not supported Exceptions). But I get a linker error:

error.cpp:6: undefined reference to error fatal_error_occurred_

I'm experienced in .NET, accessing a static field from a static method would work there... What am I missing in C++?

error.h

class error
{
private:
	static bool fatal_error_occurred_;
public:
	static bool check_fatal_error_occurred();
	static void throw_fatal(char* origin, char* error_message);
};

error.cpp

#include "error.h"

bool error::check_fatal_error_occurred()
{
	return error::fatal_error_occurred_;
}

thanks!

thomasvt:
I'm experienced in .NET, accessing a static field from a static method would work there... What am I missing in C++?

You've got the declaration, but are missing the definition:

bool error::fatal_error_occurred_ = false;

Hi, thanks..

I added that line you're showing to the .h earlier, but then the linker said something about duplicate definition.

But as you advised the same thing, I tried putting that line in the cpp and that works!

But now I'm confused: if an include is nothing more than a "copy paste", I really don't see the difference between putting that assignment statement in the header vs cpp. But apparently there is a difference.

thomasvt:
Hi, thanks..

I added that line you're showing to the .h earlier, but then the linker said something about duplicate definition.

But as you advised the same thing, I tried putting that line in the cpp and that works!

But now I'm confused: if an include is nothing more than a "copy paste", I really don't see the difference between putting that assignment statement in the header vs cpp. But apparently there is a difference.

It's not an assignment statement. It's a variable definition (and initialization). That's what actually allocates the memory space for the variable and it belongs ONLY in the .cpp file. If you did in the .h, and that .h was #include(d) into multiple other files, you'd have a multiple definition error.

Ahaa.. yes, wait... googling ... ok, apparently I also misunderstood pragma once a bit. I didn't realize each cpp file gets compiled separately. So, pragma once restricts a file to once per COMPILATION (aka cpp file in my case)

So, then I understand what you say now: declarations are ok to recur throughout multiple .obj, but multiple definitions would be ambiguous... Therefore definitions should not be in .h file as they would get compiled into multiple obj files and clash...

thanks!