gpt4 book ai didi

c - gcc 的配置选项如何确定默认枚举大小(短或不短)?

转载 作者:太空狗 更新时间:2023-10-29 17:24:05 26 4
gpt4 key购买 nike

我尝试了一些 gcc 编译器来查看默认的枚举大小是短的(至少一个字节,强制使用 -fshort-enums)还是不短(至少 4 个字节,强制的)使用 -fno-short-enums):

user@host:~$ echo '_Static_assert(4 == sizeof(enum{E}), "enum size is not 4");' | x86_64-linux-gnu-gcc -fsyntax-only -xc - && echo "OK, enum size is 4 on x86_64-linux-gnu"
OK, enum size is 4 on x86_64-linux-gnu

user@host:~$ echo '_Static_assert(4 == sizeof(enum{E}), "enum size is not 4");' | arm-linux-gnueabihf-gcc -fsyntax-only -xc - && echo "OK, enum size is 4 on arm-linux-gnueabihf"
OK, enum size is 4 on arm-linux-gnueabihf

user@host:~$ echo '_Static_assert(4 == sizeof(enum{E}), "enum size is not 4");' | /opt/Atollic_TrueSTUDIO_for_STM32_x86_64_9.1.0/ARMTools/bin/arm-atollic-eabi-gcc -fsyntax-only -xc -
<stdin>:1:1: error: static assertion failed: "enum size is not 4"

user@host:~$ echo '_Static_assert(4 == sizeof(enum{E}), "enum size is not 4");' | /opt/Atollic_TrueSTUDIO_for_STM32_x86_64_9.1.0/ARMTools/bin/arm-atollic-eabi-gcc -fno-short-enums -fsyntax-only -xc - && echo "OK, enum size is 4 on arm-atollic-eabi with -fno-short-enums"
OK, enum size is 4 on arm-atollic-eabi with -fno-short-enums

如您所见,短是嵌入式目标的默认设置,而 no-short 是托管平台的默认设置。这对于提高托管平台上的二进制兼容性是有意义的。现在:

根据构建 gcc 时的配置选项,枚举是否会变短的规则是什么?它记录在何处?

编辑:

正如 Lundin 的回答中指出的那样,the gcc manual指出

On some targets, -fshort-enums is the default; this is determined by the ABI.

我的问题是:如何对 ABI 的依赖性,它在哪里记录? gcc 源是否包含一种将体系结构(例如 arm-linux-gnueabihf)映射到 ABI 的数据库,以及一种为每个 ABI 指定所有选项(例如短枚举或非短枚举)的数据库?还是散落在整个源代码树中的所有硬编码魔法?

最佳答案

在 gcc 手册中,查找实现定义的行为。 Chapter 4.9 .

The integer type compatible with each enumerated type (C90 6.5.2.2, C99 and C11 6.7.2.2).

Normally, the type is unsigned int if there are no negative values in the enumeration, otherwise int. If -fshort-enums is specified, then if there are negative values it is the first of signed char, short and int that can represent all the values, otherwise it is the first of unsigned char, unsigned short and unsigned int that can represent all the values.

On some targets, -fshort-enums is the default; this is determined by the ABI.

斜体 部分引用自 C 标准的实现定义行为。如您所见,类型是自适应的,具体取决于存在哪些枚举常量。对于不同的 enum 类型,它不需要在您的程序中始终具有相同的大小。

优化设置可能很重要,因为在某些机器上 4 字节 enum 可能比 1 字节枚举更快。

关于c - gcc 的配置选项如何确定默认枚举大小(短或不短)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54348245/

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