我在Keil中使用C99编程微处理器,并且难以使用结构来定义静态const。 以下compliles没有问题:
static uint8_t const addr1 = 0x76;
static uint8_t const addr = addr1;
但以下情况并非如此:
typedef struct
{
uint8_t const address;
} bmp280_t;
static bmp280_t bmp280_0 = {
.address = 0x76,
};
static uint8_t const addr2 = bmp280_0.address;
最后一行导致编译错误:
...... \ main.c(97):错误:#28:表达式必须有一个常量 value static uint8_t const addr2 = bmp280_0.address;
我试图在visual studio中复制,但两种情况都不能编译。我不知道这是因为它是以cpp编译还是使用不同的标准..
答案 0 :(得分:4)
您正在使用的初始值设定项(即:bmp280_0.address
)不是编译时常量。但是,您可以执行以下操作:
#define ADDRESS 0x76
typedef struct
{
uint8_t const address;
} bmp280_t;
static bmp280_t bmp280_0 = {
.address = ADDRESS,
};
static uint8_t const addr2 = ADDRESS;
也就是说,定义一个预处理器宏ADDRESS
,当预处理器替换它时,它将导致编译时常量0x76
,并将此预处理器宏用作初始化器。