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

后端 未结 2 1007
日久生厌
日久生厌 2021-01-22 05:36

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

  • GCC
  • Clang
  • MSVC
2条回答
  •  走了就别回头了
    2021-01-22 05:47

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

    #include 
    
    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).

提交回复
热议问题