对于我正在从事的项目,我想要一个静态初始化的、不可变的全局数组——具体来说是一个数组,而不是一个枚举
。据我所知,最好的方法是使用 extern const
数组。但是,当我尝试初始化和声明任何数组 foo
时,我收到两个不同但明显相关的编译器错误:
error: conflicting types for `foo'
error: invalid initializer
对于我的 .c
文件外部范围中的每次初始化,都会重复这些操作。前一个错误后面总是跟着一条注释:“前一个‘foo’的声明在这里
”并指向头文件中数组的声明。
在以下示例中...
#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
};
关于c - extern const 数组声明/初始化错误(无效的初始化器/冲突类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55499412/