GCC/Clang/MSVC extension for specifying C enum size?

烈酒焚心 提交于 2019-12-02 02:13:36

问题


Is there any extension feature to specify size of C enum on each compiler?

  • GCC
  • Clang
  • MSVC

回答1:


With GCC, you cannot specify the exact length, but you can have it take up the shortest length possible with -fshort-enums. Example:

#include <stdio.h>

typedef enum
{
    f1, f2
} foo;

int main()
{
    printf("%i\n", sizeof(foo));
    return 0;
}

Compile:

gcc program.c -fshort-enums

Output:

1

However, if you ever want to link to anything, you have to make sure that whoever looks at your headers also uses -fshort-enums or it will not be ABI compliant (and you will see some really funny errors).




回答2:


C++11 introduced a standardized way to do this, but since this is C you'll have to settle for a more simple method of making the last enum INT_MAX or a value thats large enough so that only the type you want can hold it (this is what the DirectX SDK does). Unfortunatly there is no way to force a maximum size (at least not without compiler specific extensions).



来源:https://stackoverflow.com/questions/6159677/gcc-clang-msvc-extension-for-specifying-c-enum-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!