以下代码按预期使用avr++4.8.1编译:(代码必须在不同的翻译单元中拆分才能看到任何结果,因为优化器将在内联指令时删除所有效果)
十.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.cpp:8:32: warning:'progmem‘属性指令忽略了-Wattributes“,并且代码被中断,因为var x存储为ram而不是闪存。
下一个问题是类方法的使用,类方法必须处理与闪存或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 };因为"void () const“的限定符const不足以确定var存储在flash/ram中。这有什么诡计吗?
发布于 2013-06-24 08:48:26
我问题的第一部分的解决办法很简单:
extern const X x __attribute__ ((__progmem__)) = { 1 };
extern const X x [[gnu::__progmem__]] = { 1 };问题在于属性之前缺少的gnu::。
https://stackoverflow.com/questions/16979123
复制相似问题