6

On an embedded system we use global variables often to keep dynamic memory consumption on heap and stack low. But global variables are also considered bad programming practice if they aren't used in a global sense, i.e. they are used only inside one or two functions.

So I really want to make use of the possibilites to protect my code from myself. Of course, the instantiation mechanism of c++ is to avoid on an embedded system with low resources, like an arduino. So I write classes with static members (and member functions) only. Many of the libraries shipped with arduino seem to work this way, too.

I'm curious if there's a single drawback of moving static variables or even const arrays (designed for deposit in progmem) from global namespace to a class namespace and making them private?

I'm primarily interested in drawbacks arising from the combination of OOP with the arduino platform (using an arduino uno) with avr-gcc.

VE7JRO
2,51519 gold badges27 silver badges29 bronze badges
asked Dec 25, 2014 at 21:50

1 Answer 1

3

I can see no specific drawback in using static class members instead of global variables on Arduino. They will be managed the same in the end program.

The only difference I can see may arise based on how you design your classes (if design is correct, then no special problem shall arise):

Let's suppose you decale a class A:

class A {
 public:
 void f();
 void g();
 ...
 static void z();
 private:
 static int myStaticField;
 ...
};

if you need an instance of A for method f(), which does not need myStaticField, then that field exists anyway in your SRAM space.

But this is a corner-case, as in good OOD, myStaticField should be needed as soon as you need to work with class A (whatever method youwant to use).

answered Dec 25, 2014 at 22:06
2
  • But if I make instances of A, myStaticField will get reserved in RAM (or wherever) once only, won't it? Commented Dec 26, 2014 at 11:50
  • 1
    Yes, of course, that is the difference between static and non static members. Commented Dec 26, 2014 at 14:59

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.