Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

namespace global variable losing value (C++)

So in my namespace's .h file, I have

namespace wtvr{
    static Matrix m;
    void LoadIdentity(void);
};

and in its .cpp file, I have

namespace wtvr{
    void LoadIdentity(void){
        m = Identity();
        m.display();// trace for debugging
    }
};

else where in the main program

wtvr::LoadIdentity();
wtvr::m.display();

The first display() prints the identity matrix to the screen from within the LoadIdentity() function, but the second, which is after the function returns, displays all zeros. Why are my values disappearing? Is there a different way I should be making my global? Thanks

like image 610
user980058 Avatar asked Sep 06 '26 07:09

user980058


2 Answers

You've declared static Matrix m; in the header file. This means that each .cpp file that includes that header will get its own version of m.

instead you need to make it a global (although namespace-scoped) variable.

In the header file:

namespace wtvr{
extern Matrix m;
};

In any of the .cpp files:

namespace wtvr{
Matrix m;
};
like image 109
Jonathan Potter Avatar answered Sep 07 '26 22:09

Jonathan Potter


You've declared the variable as static, which means each translation unit (.cpp file) has its own copy of it. You probably meant this:

.h file:

namespace wtvr{

extern Matrix m;  //declare for use from everywhere
void LoadIdentity(void);

}

.cpp file:

namespace wtvr{

Matrix m;  //define in exactly one .cpp file

void LoadIdentity(void)
{
  m = Identity();
  m.display();// trace for debugging
}

}
like image 27
Angew is no longer proud of SO Avatar answered Sep 07 '26 20:09

Angew is no longer proud of SO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!