I'm trying to abstract away some GLFW input code by using a global variable state to keep track of key presses.
I thought using namespaces would be nice, so I thought doing something like:
namespace InputState { namespace KeyPressed { static bool left = false; static bool right = false; static bool down = false; static bool up = false; }; }; and then accessing these variables like
if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS) { InputState::KeyPressed::left = true; } else { InputState::KeyPressed::left = false; } and
if (InputState::KeyPressed::left) { body->velocity.x -= 0.25f; } would be really easy and visually/architecturally appealing, but as I've found out, creating static variables in namespaces brings some weird behavior that make this not work as intended.
I've tried using extern, but that gave me linker errors stating that there was a redefinition of the variables. I've triple checked that I have my header guards in place.
Is there some way I can get this working where I truly have a global variable within a namespace or is this just not possible/not intended behavior for namespaces?
extern(such as keeping the initialization of the variables in the header) that made you believe that namespaces are relevant to the issue. (Header guards only protect against multiple inclusions in a translation unit. If you include a definition in multiple translation units you still get multiple definitions.)structwhich is passed by reference (orconstreference) where ever it's modified (or evaluated). A side effect would be that yourexternissue would vanish.struct1.) You don't need any global variable. A local variable inmain()has sufficient life-time as well. 2.) The respective function to read out the keyboard state has to get a reference to that variable. 3.) Where you want to check the current keyboard state, you have to pass a const reference to that struct.