如何使用extern值创建表(数组)?

时间:2010-07-26 22:49:27

标签: c++ c extern array-initialization

我想创建一个数据指针,数据大小和数据版本的静态(文件范围)表。问题是数据在外部文件中,但在extern文件中是常量。

实施例

file1.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) / sizeof(data1[0]);
    const unsigned int data1_version = 1;

file2.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) / sizeof(data2[0]);
    const unsigned int data2_version = 1;

的main.c

struct Data_Info
{
  unsigned char * data_ptr;
  unsigned int    data_size;
  unsigned int    data_version;
};

extern const unsigned char data1[];
extern const unsigned int  data1_size;
extern const unsigned int  data1_version;

extern const unsigned char data2[];
extern const unsigned int  data2_size;
extern const unsigned int  data2_version;

static struct Data_Info  Data_Info_Table[] =
{
  // How to set this up??
  // The compiler wants constant expressions here,
  //    and the extern is not considered a constant expression
  // This is what I tried:
  { data1, data1_size, data1_version},
  { data2, data2_size, data2_version},
};

int main(void)
{
  return 0;
} 

我正在使用Green Hills Compiler,4.2.3。确切的错误消息:

error #28, expression must have a constant value.

见我之前的帖子:
C: External const ints in a array of const struct

注意:包含C ++标记,因为这也适用于C ++

4 个答案:

答案 0 :(得分:2)

你尝试过吗? (其中X为0或1。)

struct Data_Info    
{    
  unsigned char const * data_ptr;    
  unsigned int    data_size;    
  unsigned int    data_version;    
};    

fileX.h

extern const struct Data_Info data_infoX;

fileX.c

const struct Data_Info data_infoX = { dataX, dataX_size, dataX_version };

的main.c

const struct Data_Info const * Data_Info_Table[] = 
{ 
  &data_info1,
  &data_info2
}; 

答案 1 :(得分:1)

问题是编译器不知道要放入该字段的data_sizedata_version成员的值。有几种方法可以解决这个问题,而不用太多大惊小怪。

方法1:

#include "data1.c"
#include "data2.c"

...
static struct Data_Info  Data_Info_Table[] =
{
  { data1, sizeof(data1), 1},
  { data2, sizeof(data2), 1},
};

方法2:

struct Data_Info
{
  unsigned char * data_ptr;
  unsigned int *  data_size;
  unsigned int *  data_version;
};

...

static struct Data_Info  Data_Info_Table[] =
{
  { data1, &data1_size, &data1_version},
  { data2, &data2_size, &data2_version},
};

jyoung已经证明,第三种方法是在单独的数据文件中分配成员,并将其地址包含在Data_Info_Table中。

答案 2 :(得分:0)

定义常量时,请使用extern关键字。

答案 3 :(得分:0)

我不是那么多C专家,但是不同翻译单元的初始化顺序很可能是未定义的(我知道它在C ++中是未定义的,如果C中的行为不同,那将是一个巨大的兼容性中断),所以即使编译器允许它也是危险的。

现在,添加C ++标签很可能不会有多大帮助,因为AFAIK不仅依赖于语言,还依赖于语言的特定版本:C89 / C99。在C ++中,如果将初始化移动到头文件中的常量声明,它就可以工作。再说一次,我不是C专家。