Home > front end >  Global namespace variables without translation unit issues?
Global namespace variables without translation unit issues?

Time:11-26

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?

CodePudding user response:

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?

If you want to use these variables in other source file then you can do so using extern as follows:

myheader.h

#ifndef MYHEADER_H
#define MYHEADER_H
namespace InputState
{
    namespace KeyPressed
    {
        extern bool left, right, down, up;
    
    };
};

#endif

mysource.cpp

#include "myheader.h"
namespace InputState
{
namespace KeyPressed
    {
         bool left = false;
         bool right = false;
         bool down = false;
         bool up = false;
        }
 }

main.cpp

#include "myheader.h"
#include <iostream>

int main()
{
    std::cout<<InputState::KeyPressed::left<<std::endl;
    InputState::KeyPressed::left = true;
    std::cout<<InputState::KeyPressed::left<<std::endl;
}

Just like i have used the variable InputState::KeyPressed::left in main.cpp you can now use it in your own file and it will work.

The above program works as can be seen here.

  •  Tags:  
  • c
  • Related