Hi guys, I'm having difficulty understanding how to get some global variables happening in OpenGL. Lets say I have a calculator on which I have a couple of buttons such as 0-9, X, multiply and equals. What I want to do is to be able to declare the variable X somewhere as something e.g. 3.14 - the value of pi for example and then to call that value from a variety of places.
In OpenGL, if my understanding serves me correctly, all the magic happens inside the PainGL function which basically means that if I initialise this variable within the initialise function, it will go out of scope by the time that we get into the PainGL function and simply dumping it outside all functions produces an error. On LearnCPP website, they suggest to create a global.h with
and also a global.cpp with
And then to simply include the global.h into whatever header you desire, however upon trying this method, I got the same error as I did when I simply dumped the initialisation outside of all functions inside my GLWidget class. I tried instantiating it inside the main.cpp function and inside mainwindow.cpp, however in both instances, I'm unable to gain access to those objects from within my GLWidget.cpp class.
Any ideas?


Reply With Quote

I suggest to do it the regular C++ way -- assuming you have a class somewhere that contains your OpenGL code, store your "x" as a member variable of that class. Then you can access it from any code from that class and if you make the variable public or provide a getter for it, you'll be able to access it from outside the class too. Furthermore if the variable is constant, you can define it as "const int x" in the class or in any header file.
Bookmarks