Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ARM C++ - how to put const members in flash memory?

I have this code

class IO {
 public:       
    IO(LPC_GPIO_TypeDef* port, int pin) : _pin(pin), _port(port) {};        

    const int _pin;
    LPC_GPIO_TypeDef* const _port;


    void test() {
        LPC_GPIO0->FIOSET = 0;
    }

};

IO led1(LPC_GPIO0, 5);

int main() {
    led1.test();

    return 0;
}

When i compile it i get

text       data     bss     dec     hex  filename
656        0          8     664     298  lpc17xx

I'd expect const _port and _pin variables be stored in flash since they are marked const and initialization values are known at compile time, but they are allocated in .bss section. Is there any way to make them reside in flash memory?

EDIT: I tried this:

struct IO {

    LPC_GPIO_TypeDef* port;
    int pin;

    void test() const {
        //_port->FIOSET = _pin;

        LPC_GPIO0->FIOSET = 0;
    }

};

const IO led1 = {LPC_GPIO0, 5};

text       data     bss     dec     hex filename
520        0          0     520     208 lpc17xx

seems to do the trick. Why doesn't it work with classes?

like image 309
walmis Avatar asked Oct 09 '22 19:10

walmis


1 Answers

The parameters to the constructor are variables, you are assigning a variable to a const, which is OK in a constructor, but while a smart optimiser might spot the occurrence of the constant expressions in the static instantiation, you are probably asking a lot, since the general case requires the constructor to accept variables, and the code will be generated for the general case.

You could probably achieve what you want using a template class, and pass the port/pin as template arguments rather than constructor arguments.

It may be compiler dependent, but in my experience you have to declare a variable as static const to force it into Flash, but that will not work for what you are trying to do.

like image 125
Clifford Avatar answered Oct 12 '22 11:10

Clifford