3

使用外部常量整数初始化结构数组时,我收到一条错误消息“表达式必须具有常量值”。

文件1.c:

const unsigned char data1[] =
{
    0x65, 0xF0, 0xA8, 0x5F, 0x5F,
    0x5F, 0x5F, 0x31, 0x32, 0x2E,
    0x31, 0xF1, 0x63, 0x4D, 0x43, 
    0x52, 0x45, 0x41, 0x54, 0x45,
    0x44, 0x20, 0x42, 0x59, 0x3A,
    0x20, 0x69, 0x73, 0x70, 0x56, 
// ...
};
const unsigned int data1_size = sizeof(data1);

文件2.c:

const unsigned char data2[] =
{
    0x20, 0x44, 0x61, 0x74, 0x61,
    0x20, 0x52, 0x6F, 0x77, 0x20,
    0x3D, 0x20, 0x34, 0x38, 0x12, 
//...
};
const unsigned int data2_size = sizeof(data2);

Get_Byte.c:

extern const unsigned char * data1;
extern const unsigned int    data1_size;
extern const unsigned char * data2;
extern const unsigned int    data2_size;

struct Array_Attributes
{
    const unsigned char *    p_data;
    const unsigned int       size;
};

const struct Array_Attributes Data_Arrays[] =
{
    {data1, data1_size},  // Error message is for data1_size here.
    {data2, data2_size},  // Another error message generated for data2_size here.
};

我还从of 字段中删除了const限定符并得到相同的错误消息。sizeArray_Attributes

data1_size为什么编译器在不同的翻译单元中data2_size抱怨常量值表达式?const unsigned int

我想要一个在编译时生成的 [array address, array size] 常量数组。

ccarm在 Windows XP 上使用 Green Hills 4.24,C 语言不是C++。

4

1 回答 1

7

在这种情况下,C 的const限定符与编译器认为的 a 几乎没有关系。constant expression在初始化程序中,即

const struct attributes attrs[] = {
    { expr1, expr2 }, 
    ...
}

expr1并且expr2必须具有非常具体的形式才能被编译器接受。这些限制的结果是表达式可以在不从程序变量中获取的情况下进行评估,因为这些在编译时不存在。

您正在尝试使用data1_sizeand data2_size,这些规则不是编译时间常量。

顺便说一句,声明

const unsigned char data1[] = { ... };

extern const unsigned char *data1;

不兼容,会导致代码中的错误。后者应该是

extern const unsigned char data1[];
于 2010-04-05T18:23:02.400 回答