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.
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.