gpt4 book ai didi

c - 相同枚举类型的不同大小

转载 作者:太空狗 更新时间:2023-10-29 14:53:50 28 4
gpt4 key购买 nike

以下代码中枚举类型的大小不同,为什么?枚举类型的声明是否会导致 gcc 将其视为 signed int?而这个特性在我的项目中造成了一个问题,例如,一个枚举类型的大小在“file_1.c”中为 1,但在“file_2.c”中它的大小为 4。

我的测试代码:

enum foo foo_test(void);

enum foo {
FOO_0
};

enum bar {
BAR_0
};

int main(int argc, char **argv)
{
printf("sizeof(enum foo) %d, sizeof(enum bar) %d\n", sizeof(enum foo), sizeof(enum bar));
return 0;
}
  • 当我在我的嵌入式项目中使用 arm-none-eabi-gcc v4.9.3 编译它时

    • 输出是sizeof(enum foo) 4, sizeof(enum bar) 1
  • 当我在 Windows 中使用 gcc v4.8.3 编译它时

    • gcc -Wall -o sizeofTest.exe sizeofTest.c 编译
      • 输出是sizeof(enum foo) 4, sizeof(enum bar) 4
    • gcc -Wall -fshort-enums -o sizeofTest.exe sizeofTest.c 编译
      • 输出是sizeof(enum foo) 4, sizeof(enum bar) 1

最佳答案

中询问关于特殊结果的问题是如此常见,这里的原因是未定义的行为。 C11标准草案n1570 6.7.2.3p3 :

  1. A type specifier of the form

    enum identifier

    without an enumerator list shall only appear after the type it specifies is complete.

以及 C11 6.7.2.2p4 中的完整性:

  1. [...] The enumerated type is incomplete until immediately after the } that terminates the list of enumerator declarations, and complete thereafter.

由于 constraints 部分中的 shall 被违反,符合标准的编译器必须输出诊断消息 - 然而默认情况下 GCC 不是符合标准的实现,除非您提出要求成为-pedantic :

ISO C forbids forward references to ‘enum’ types [-Werror=pedantic]
enum foo foo_test(void);
^

现在,那里的编译器似乎对任何类型都使用了最短 可能的枚举。由于您使用了 enum foo 之前它实际上定义了其中的内容,编译器不得不求助于int对于它的类型,否则 char被使用了。它可以用 -fshort-enums 复制.你的程序打印 4 1 , 而这个程序打印 1 1-fshort-enums在我的 gcc 上。

#include <stdio.h>

enum foo {
FOO_0
};

enum foo foo_test(void);

enum bar {
BAR_0
};

int main(int argc, char **argv)
{
printf("sizeof(enum foo) %zu, sizeof(enum bar) %zu\n",
sizeof(enum foo), sizeof(enum bar));
return 0;
}

关于c - 相同枚举类型的不同大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45838943/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com