简体   繁体   English

无法使用我认为应该是编译时常数的内容初始化静态数组

[英]Can't initialize static array with what I think is supposed to be a compile-time constant

I'm trying to initialize a static array with the size based on what I think should be a compile-time constant. 我试图根据我认为应该是编译时常量的大小来初始化静态数组。

This is easily fixable but simply not using static, but I didn't expect this issue to show up at all. 这很容易解决,但根本不使用静态,但是我完全没有想到这个问题。 This might cause me other issues in the future. 将来可能会导致我其他问题。

The relevant sections: 相关章节:

typedef struct {
    GPIO_TypeDef* Port;
    uint16_t Pin;
} PortPin;

typedef struct {
    I2C_HandleTypeDef *Handle;
    uint16_t Address;
    PortPin Interrupt;
    PortPin Shutdown;
} VL53L1_Dev_t;

//This one is bigger but I've kept it short to keep it readable. It's 3 elements in my code
static VL53L1_Dev_t Sensors[] = {
    {//1
            &hi2c2,
            0x52,
            {
                    GPIOA,
                    GPIO_PIN_11
            },
            {
                    GPIOA,
                    GPIO_PIN_10
            }
    }
}
static const int sensorCount = sizeof(Sensors)/sizeof(Sensors[0]);
static uint8_t encodedData[sensorCount * 2];//Compiler doesn't like this part

Since Sensors is fully defined on compile-time, I expected sensorCount to also be a compile-time constant. 由于Sensors是在编译时完全定义的,因此我希望sensorCount也是一个编译时常量。 Which apparently it isn't because I can't use it to declare and initialize static arrays. 这显然不是因为我无法使用它来声明和初始化静态数组。 I don't understand why. 我不明白为什么。

The size of an array declared at file scope must be an integer constant expression . 在文件作用域声明的数组的大小必须是整数常量表达式 It is defined in section 6.6p6 of the C standard : 它在C标准的 6.6p6节中定义:

An integer constant expression shall have integer type and shall only have operands that are integer constants, enumeration constants, character constants, sizeof expressions whose results are integer constants, _Alignof expressions, and floating constants that are the immediate operands of casts. 整数常量表达式应具有整数类型,并且仅应具有作为整数常量,枚举常量,字符常量, sizeof表达式(其结果为整数常量), _Alignof表达式和浮点常量(它们是强制转换的立即数)的操作数。 Cast operators in an integer constant expression shall only convert arithmetic types to integer types, except as part of an operand to the sizeof or _Alignof operator . 整数常量表达式中的强制转换运算符只能将算术类型转换为整数类型,除非作为sizeof_Alignof运算符的操作数的一部分。

So the contents of a variable, even if declared const , are not part of such an expression. 因此,即使声明为const ,变量的内容也不是该表达式的一部分。

If however you define sensorCount as a macro, the expression sizeof(Sensors)/sizeof(Sensors[0]) is a compile time constant. 但是,如果将sensorCount定义为宏,则表达式sizeof(Sensors)/sizeof(Sensors[0]) 一个编译时间常数。

#define SENSOR_COUNT  (sizeof(Sensors)/sizeof(Sensors[0]))
static uint8_t encodedData[SENSOR_COUNT * 2];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM