ARM C ++ - 如何将const成员放在闪存中? [英] ARM C++ - how to put const members in flash memory?

查看:263
本文介绍了ARM C ++ - 如何将const成员放在闪存中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码

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;
}

当我编译我得到

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

我会期望将const _port和_pin变量存储在flash中,因为它们被标记为const,并且编译时已知初始化值,但是它们在.bss部分中分配。有没有办法让他们居住在闪存?

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?

编辑:
我试过这个:

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?

推荐答案

构造函数的参数是变量,你将一个变量分配给一个const ,这在构造函数中是可以的,但是当智能优化器可能会发现静态实例化中的常量表达式的发生时,您可能会问很多,因为一般情况需要构造函数接受变量,并且代码将为一般情况生成。

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.

它可能是编译器依赖的,但根据我的经验,你必须声明一个变量作为静态const来强制进入Flash,但这不会适用于什么你正在努力。

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.

这篇关于ARM C ++ - 如何将const成员放在闪存中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆