c++11通用属性与avr __programme__

c++11 generalized attributes with avr __progmem__

本文关键字:avr programme 属性 c++11      更新时间:2023-10-16

以下代码在avr-g++ 4.8.1下按预期编译:(代码必须分成不同的翻译单元才能看到任何结果,因为优化器会在内联指令时删除所有效果)

x.h:

struct X
{
    uint8_t a;
};

x.cpp:

extern const X x __attribute__ ((__progmem__)) = { 1 };

main.cpp:

#include "x.h"
extern const X x __attribute__ (( __progmem__ )); 
int main()
{   
    PORTB = pgm_read_byte(& (x.a));
    return 0;
}

导致(objdump -d):

0000001a <x>:
  1a:   01 00                                               ..
  ...
  2e:   ea e1           ldi r30, 0x1A   ; 26
  30:   f0 e0           ldi r31, 0x00   ; 0
  32:   c8 95           lpm

结果很好。

问:为什么不能用c++11写:

 extern const X x [[__progmem__]] = { 1 };

这会导致一个警告"x.cp:8:32: warning: ' program ' attribute指令被忽略[- watattributes]"并且代码被破坏,因为var x被存储到ram而不是flash中。

下一个问题是使用类方法,该类方法必须处理不同于flash或ram中存储的数据成员。

a.h:

    class A
    {
        private:
            uint8_t a;
        public:
            constexpr A( uint8_t _a): a(_a) {}
            void Store() const; // Q:should be something like const __attribute__((__PROGMEM__)) ???
            void Store();
    };

a.cpp:

   #include "a.h"
    void A::Store() const
    {   
        PORTB=pgm_read_byte(&a);
    }   
    void A::Store() 
    {   
        PORTB=a;
    }   
    extern const A a_const PROGMEM ={ 0x88 };
    A a_non_const={ 0x99 };

main.cpp:

extern const A a_const;
extern A a_non_const;

int main()
{
    a_const.Store();
    a_non_const.Store();
    return 0;
}

代码工作正常,但如果var声明是:

extern const A a_const_non_flash={ 0x11 };

因为限定符const到"void Store() const"不足以决定var是否存储在flash/ram中。有什么诀窍吗?

我问题的第一部分的解决方案很简单:

extern const X x __attribute__ ((__progmem__)) = { 1 };
extern const X x [[gnu::__progmem__]] = { 1 };

问题是属性前缺少gnu::