[英]C - forward declaration of enums?
Forward declaration of enums in C does not work for me. C 中枚举的前向声明对我不起作用。 I searched the internet and stackoverflow but all of the questions regarding forward declarations of enumerators refer to c++.
我搜索了互联网和 stackoverflow,但所有关于枚举数前向声明的问题都是指 C++。 What do you do for declaring enumerators in C?
在 C 中声明枚举器是做什么的? Put them at the top of each file (or in an include) so that all functions in the file can access them?
将它们放在每个文件的顶部(或包含),以便文件中的所有函数都可以访问它们? Thanks
谢谢
Put them in a header so that all files that need them can access the header and use the declarations from it.将它们放在标题中,以便所有需要它们的文件都可以访问标题并使用其中的声明。
When compiled with the options:使用选项编译时:
$ /usr/bin/gcc -g -std=c99 -Wall -Wextra -c enum.c
$
GCC 4.2.1 (on MacOS X 10.7.1) accepts the following code: GCC 4.2.1(在 MacOS X 10.7.1 上)接受以下代码:
enum xyz;
struct qqq { enum xyz *p; };
enum xyz { abc, def, ghi, jkl };
Add -pedantic
and it warns:添加
-pedantic
并警告:
$ /usr/bin/gcc -g -std=c99 -Wall -Wextra -pedantic -c enum.c
enum.c:1: warning: ISO C forbids forward references to ‘enum’ types
enum.c:5: warning: ISO C forbids forward references to ‘enum’ types
$
Thus, you are not supposed to try using forward declarations of enumerated types in C;因此,您不应该尝试在 C 中使用枚举类型的前向声明; GCC allows it as an extension when not forced to be pedantic.
GCC 允许将其作为不被迫迂腐的扩展。
You can't "forward-declare" enums because the compiler won't know the size of the enum.您不能“向前声明”枚举,因为编译器不知道枚举的大小。 The C standard says " Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined, but shall be capable of representing the values of all the members of the enumeration ".
C 标准说“每个枚举类型应与 char、有符号整数类型或无符号整数类型兼容。类型的选择是实现定义的,但应能够表示枚举的所有成员的值” .
I came here having the same error, but there is not really much information provided here on the code/error.我来到这里时遇到了同样的错误,但这里没有提供太多关于代码/错误的信息。
My Makefile-flags are: -Wall -Wextra -Werror -pedantic -std=c17
我的 Makefile 标志是:
-Wall -Wextra -Werror -pedantic -std=c17
In my header I have the following enum
:在我的标题中,我有以下
enum
:
typedef enum
{
IS_HEAD = 1,
IS_VALUE = 2,
IS_SIDE
} CoinResult;
The tutorials here and there这里和那里的教程
Would recommend to use something like this:建议使用这样的东西:
enum CoinResult cr;
cr = IS_SIDE;
This results in the error stated by the OP.这会导致 OP 所述的错误。
Solved by using:通过使用解决:
CoinResult cr = IS_SIDE;
Not sure which C-Standard, Code or reference OP was using, but I somewhat agree: Most tutorials and solutions for this relatively simple issue are kinda ambiguous.不确定使用的是哪个 C 标准、代码或参考 OP,但我有点同意:这个相对简单的问题的大多数教程和解决方案都有些模棱两可。
CoinResult isn't an enum, it's a type. CoinResult 不是枚举,而是一种类型。 If you had
如果你有
enum CoinResult {
IS_HEAD = 1,
IS_VALUE = 2,
IS_SIDE,
};
then然后
enum CoinResult cr;
would be correct.会是正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.