对于我正在从事的项目,我需要一个静态初始化的,不可变的全局数组,特别是一个数组,而不是enum
。据我所知,最好的方法是使用extern const
数组。但是,当我尝试初始化并声明任何数组foo
时,会出现两个不同但显然相关的编译器错误:
error: conflicting types for `foo'
error: invalid initializer
在我的.c
文件的外部范围中的每次初始化都重复这些操作。这些错误中的前一个总是紧随其后的注释读为“ previous declaration of `foo' was here
”,并指向头文件中数组的声明。
在下面的示例中...
#ifndef __MWE__
#define __MWE__
extern const int foo[8];
#endif /* MWE */
#include "mwe.h"
const int foo[0] = 0;
const int foo[1] = 42;
const int foo[2] = 69;
const int foo[3] = 420;
const int foo[4] = 9001;
int main(int argc,char**argv){return 0;}
...我遇到以下错误...
mwe.c:3:11: error: conflicting types for ‘foo’
const int foo[0] = 0;
^~~
In file included from mwe.c:1:0:
mwe.h:4:18: note: previous declaration of ‘foo’ was here
extern const int foo[5];
^~~
mwe.c:3:20: error: invalid initializer
const int foo[0] = 0;
^
mwe.c:4:11: error: conflicting types for ‘foo’
const int foo[1] = 42;
^~~
In file included from mwe.c:1:0:
mwe.h:4:18: note: previous declaration of ‘foo’ was here
extern const int foo[5];
^~~
mwe.c:4:20: error: invalid initializer
const int foo[1] = 42;
^~
mwe.c:5:11: error: conflicting types for ‘foo’
const int foo[2] = 69;
^~~
In file included from mwe.c:1:0:
mwe.h:4:18: note: previous declaration of ‘foo’ was here
extern const int foo[5];
^~~
mwe.c:5:20: error: invalid initializer
const int foo[2] = 69;
^~
mwe.c:6:11: error: conflicting types for ‘foo’
const int foo[3] = 420;
^~~
In file included from mwe.c:1:0:
mwe.h:4:18: note: previous declaration of ‘foo’ was here
extern const int foo[5];
^~~
mwe.c:6:20: error: invalid initializer
const int foo[3] = 420;
^~~
mwe.c:7:11: error: conflicting types for ‘foo’
const int foo[4] = 9001;
^~~
In file included from mwe.c:1:0:
mwe.h:4:18: note: previous declaration of ‘foo’ was here
extern const int foo[5];
^~~
mwe.c:7:20: error: invalid initializer
const int foo[4] = 9001;
声明和初始化extern const
数组的正确方法是什么,这种方法无效是什么?类型冲突在哪里?为什么整数文字是整数数组元素的无效初始化器?
答案 0 :(得分:0)
每个:
const int foo[0] = 0;
const int foo[1] = 42;
const int foo[2] = 69;
const int foo[3] = 420;
const int foo[4] = 9001;
分别命名为foo
的数组变量,每个变量的大小都不同。您还尝试使用单个值初始化这些数组。这就是为什么您会得到错误。
如果要初始化数组,请执行以下操作:
const int foo[5] = { 0, 42, 69, 420, 9001 };
如果您需要基于枚举值初始化特定的索引,则可以使用指定的初始化程序来完成此操作:
enum {
E1, E2, E3, E4, E5
};
const int foo[5] = {
[E1] = 0,
[E2] = 42,
[E3] = 69,
[E4] = 420,
[E5] = 9001
};