I want to avoid global variables when using my own classes in Arduino. Here is a example.
void setup(){
/* setup here */
classA objectA;
}
void loop(){
objectA.someMethod();
}
I know that my compiler will complain about it (out of scope, etc) but is it possible to do that or just forget it and use globally?
Thanks in advance!
1 Answer 1
If you want a variable to be available within more than one function it has to be global. There is no other possible way of doing it.
If you are only using the variable in the loop() function and nowhere else you can declare it static
in loop()
, which has the same effect of making it global, but it is only possible to see it within loop()
.
You can make a pointer global, then create a new object in setup()
(using new...
) and assign it to the pointer, but that has the potential of making a mess of your heap and should be avoided unless absolutely necessary. Also it's pointless, because you don't gain anything over having the object statically created in the global scope.
-
Seems enough for me. You convinced me! :)marquesm91– marquesm912016年09月07日 22:42:25 +00:00Commented Sep 7, 2016 at 22:42
-
I read to avoid new and delete when coding for arduino. It is not my priority. I am just curious if is possible to do what I asked.marquesm91– marquesm912016年09月07日 22:45:47 +00:00Commented Sep 7, 2016 at 22:45
-
You still end up with a global variable, just a different type of variable.Majenko– Majenko2016年09月07日 22:46:22 +00:00Commented Sep 7, 2016 at 22:46
-
This answer isn't satisfying. There has to be a way to balance programmer efficiency (e.g. organize logical bits of code in classes) with memory constraints. Is there not a compiler that can optimize the end-product in the global namespace way you suggest, but also provide the developer-friendly code organization that @marquesm91 is asking for?Andrew Allbright– Andrew Allbright2016年09月08日 01:46:47 +00:00Commented Sep 8, 2016 at 1:46
-
1You could completely ignore the global space and the
setup()
function and just treatloop()
likemain()
. Stick awhile(1)
at the end ofloop()
to stop it looping, define all your variables as local toloop()
, then pass them all as parameters to where they are going. What do you end up with? You end up with global now insideloop()
and allocated on the stack instead of the BSS. Big deal. Just stick with global, it's easier.Majenko– Majenko2016年09月08日 09:52:21 +00:00Commented Sep 8, 2016 at 9:52
MyClass foo;
) you are reserving the RAM at compilation time. All other ways of doing it involve dynamic RAM allocation and that is bad on a microcontroller.