C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了C:const结构数组中的外部const int大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
当初始化具有外部常量整数的结构数组时,我收到错误消息“表达式必须具有常量值”.

FILE1.C:

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

file2.c中:

const unsigned char data2[] =
{
    0x20,0x61,0x74,0x6F,0x77,0x3D,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.
};

我还从Array_Attributes的size字段中删除了const限定符,并获得了相同的错误消息.

当data1_size和data2_size是const unsigned int但是在不同的转换单元中时,为什么编译器会抱怨常量值表达式?

我想要一个在编译时生成的[数组地址,数组大小]的常量数组.

我使用的是Green Hills ccarm 4.24,在Windows XP上,C语言不是C.

解决方法

在这种情况下,C的const限定符与编译器认为的常量表达式几乎没有关系.在初始化器中,即

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

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

您正在尝试使用data1_size和data2_size,这些规则不是编译时常量.

便说一句,声明

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

extern const unsigned char *data1;

不兼容,将导致您的代码中的错误.后者应该是

extern const unsigned char data1[];

大佬总结

以上是大佬教程为你收集整理的C:const结构数组中的外部const int全部内容,希望文章能够帮你解决C:const结构数组中的外部const int所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。