2010-04-05 52 views
3

當使用外部常量整數初始化結構數組時,出現錯誤消息「表達式必須具有常量值」。C:常量結構數組中的外部const ints

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); 

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); 

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. 
}; 

我也刪除了來自size字段Array_Attributes的限定符,並獲取相同的錯誤消息。

爲什麼編譯器在data1_sizedata2_sizeconst unsigned int但是在不同的翻譯單元中抱怨恆定值表達式?

我想要一個在編譯時生成的[數組地址,數組大小]的常量數組。

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

回答

7

C的const限定符與編譯器在本例中認爲constant expression無關。在一個初始化,即

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

expr1expr2必須具有非常特定的形式可以接受給編譯器。這些限制的結果是可以在不從程序變量中獲取的情況下評估表達式,因爲這些在編譯時不存在。

您試圖使用data1_sizedata2_size,這些規則不是編譯時間常量。

順便說一句,該聲明

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

extern const unsigned char *data1; 

是不兼容的,並會導致你的代碼中的錯誤。後者應該是

extern const unsigned char data1[]; 
+0

我的理解是'data1 []'和'* data1'是一樣的。他們有什麼不同,爲什麼會導致錯誤? – 2010-04-05 19:09:39

+0

他們可以被替換的唯一地方是在參數聲明中。 'extern char * foo'告訴編譯器'foo'是一個包含指向字符的指針的4字節變量。 'extern char bar []'告訴編譯器'bar'是一個地址常量,指向一個未知大小的字符塊。 'foo [i]'首先獲取4個字節的指針,然後加上'i',然後取消引用以獲得一個字符。 'bar [i]'取值爲'bar',加上'i'和解引用。 – 2010-04-05 19:31:57

+1

http://c-faq.com/aryptr/aryptr1.html – 2010-04-05 19:53:37