IAR EWARM(ICC)-表达式必须具有恒定值

use*_*731 2 c pointers icc iar

我正在尝试使用IAR EWARM编译以下C代码,但遇到三个编译错误(Error [Pe028]:表达式必须具有常量值)。见下文:

#include<stdio.h>
#include<stdlib.h>
#include<stdint.h>

typedef uint8_t I2C_BusIdentifier;
typedef uint8_t I2C_SlaveAddress;

typedef enum {
    I2C_BUS_STATE_UNINITIALIZED = 0,
    I2C_BUS_STATE_GPIO_HARDWARE_READY,
    I2C_BUS_STATE_READY_TO_OPERATE,
} I2C_BusState;

typedef struct BUS_I2C_BUS_INSTANCE_TYPE {
    I2C_BusIdentifier BusIdentifer;                                         // 0 for I2C0, 1 for I2C1
    I2C_BusState CurrentState;                                              // bus status
} I2C_Bus; // I²C Bus Instance Type, I2C_BusInstanceType


typedef struct DEVICE_I2C_GENERIC {
    I2C_Bus* DeviceBusPointer;
    I2C_SlaveAddress DeviceAddress;
} I2C_Device;

// inherits from I2C_Device
typedef struct DEVICE_ADC123 {
    I2C_Device Device;
} ADC123_Device;

#define NUMBER_OF_I2C_PORTS   2

static I2C_Bus g_I2C_Bus[NUMBER_OF_I2C_PORTS] = {
    { 0, I2C_BUS_STATE_UNINITIALIZED, },
    { 1, I2C_BUS_STATE_UNINITIALIZED, },
};

I2C_Bus* const g_I2C_BusPtr_Port0 = &(g_I2C_Bus[0]);
I2C_Bus* const g_I2C_BusPtr_Port1 = &(g_I2C_Bus[1]);


const ADC123_Device g_Device_ADC123_U14 = {
    { g_I2C_BusPtr_Port0, 0xAE, }, // <--- Error[Pe028]: expression must have a constant value
};

const ADC123_Device g_Device_ADC123_U15 = {
    { g_I2C_BusPtr_Port1, 0x8A, }, // <--- Error[Pe028]: expression must have a constant value
};

const ADC123_Device g_Device_ADC123_U9 = {
    { g_I2C_BusPtr_Port1, 0xAA, }, // <--- Error[Pe028]: expression must have a constant value
};

#define NUMBER_OF_ADC123_DEVICES   3

const ADC123_Device* g_ADC123_Array[NUMBER_OF_ADC123_DEVICES] = {
    &g_Device_ADC123_U14,
    &g_Device_ADC123_U15,
    &g_Device_ADC123_U9,
};

int main(void)
{
    while(1);
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我直接使用g_I2C_Bus地址而不是通过g_I2C_BusPtr_PortX指针,则一切都将编译正常:

const ADC123_Device g_Device_ADC123_U14 = {
    { &(g_I2C_Bus[0]), 0xAE, },
};

const ADC123_Device g_Device_ADC123_U15 = {
    { &(g_I2C_Bus[1]), 0x8A, },
};

const ADC123_Device g_Device_ADC123_U9 = {
    { &(g_I2C_Bus[1]), 0xAA, },
};
Run Code Online (Sandbox Code Playgroud)

我想使用const指针(g_I2C_BusPtr_Port0,g_I2C_BusPtr_Port1),因为它们在.h文件中被外部引用,而数组(g_I2C_Bus [])不会全局公开,但在特定的.c文件中是静态的。

当定义/值相等时,由于它们引用同一事物,为什么编译器对此不满意?

use*_*733 6

这是C语言的局限性。变量的值,例如

int const a = 1;
Run Code Online (Sandbox Code Playgroud)

不能在常量表达式中使用,例如初始化程序:

int b = a; /* Will not work */
Run Code Online (Sandbox Code Playgroud)

甚至没有const预选赛。原因是编译器无法知道变量的值,即使它看起来完全是微不足道的。变量,const不是一个恒定在C,它只是不能被改变的变量

全局变量的地址是另一回事。链接器可以完全控制这些变量的位置,并且可以将相同的信息用于初始化程序。

解决方法是使用预处理器:

#define g_I2C_BusPtr_Port0 (&(g_I2C_Bus[0]))
Run Code Online (Sandbox Code Playgroud)