对于我正在研究的项目,我想要一个静态初始化的,不可变的全局数组 - 特别是数组,而不是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
数组的正确方法是什么,以及这种无效的方式是什么?类型冲突在哪里,为什么整数文字对于整数数组的元素是无效的初始值设定项?
每个:
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
};