C 错误:表达式必须有一个常量值 [英] C error: expression must have a constant value

查看:55
本文介绍了C 错误:表达式必须有一个常量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些嵌入式代码以通过 SPI 与外部设备连接.该设备有几个不同长度的寄存器,为了帮助保持直线,我定义了以下结构

I am writing some embedded code to interface with an external device over SPI. The device has several registers of varying length and to help keep things straight I have defined the following structure

typedef struct
{
    uint16_t    Signed          :1;  // Register is signed or unsigned
    uint16_t    CommLengthBytes :3;  // The width of the register in bytes 
    uint16_t    Address         :12; // Register address
}ts_register;

然后我在我的源代码中定义了每个寄存器

I have then defined each register in my sources as follows

static const ts_register    SAGCYC      = {0, 1, 0x000};
static const ts_register    DISNOLOAD   = {0, 1, 0x001};
static const ts_register    LCYCMODE    = {0, 1, 0x004};
static const ts_register    IRMSA       = {0, 4, 0x31A};
static const ts_register    IRMSB       = {0, 4, 0x31B};
static const ts_register    VRMS        = {0, 4, 0x31C};

我有一个函数,它将获取一个指向 ts_registers 数组的指针,并将读取数组中所有寄存器所需的 SPI 传输排队,并调用回调函数来处理回复

I have a function that will take a pointer to an array of ts_registers and queue up the SPI transfers required to read all of the registers in the array and call a callback function to handle the reply

当我尝试按如下方式制作我想要读取的 ts_registers 数组时,我的问题出现了:

My issue comes when I try to make the array of ts_registers that I want to read as follows:

ts_register regs_to_read[3] = {VRMS, IRMSA, IRMSB};

这会产生错误:表达式必须有一个常量值"3 次(每个数组元素一次).

This generates the error: "expression must have a constant value" 3 times (once per array element).

既然它们被定义为常量,我忽略了什么?

Since they are defined as constants, what have I overlooked?

推荐答案

既然它们被定义为常量,我忽略了什么?

Since they are defined as constants, what have I overlooked?

在 C 中用 const 修饰符声明的对象不是真正的常量.const 的更好名称可能是 readonly - 它的真正含义是编译器不会让 更改它.并且您需要真正的常量来初始化具有静态存储的对象(我怀疑 regs_to_read 是全局的).

In C objects declared with the const modifier aren't true constants. A better name for const would probably be readonly - what it really means is that the compiler won't let you change it. And you need true constants to initialize objects with static storage (I suspect regs_to_read is global).

您可以尝试在其他任何使用该数组之前调用的函数中分配 regs_to_read.

You could try assigning regs_to_read in a function called before anything else uses that array.

这篇关于C 错误:表达式必须有一个常量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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