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.

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.