Is there any extension feature to specify size of C enum
on each compiler?
- GCC
- Cla开发者_JS百科ng
- MSVC
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).
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).
With clang you can use this:
enum Tristate : char { Yes, No, Maybe };
If you want to typedef
, ensure you include the size specifier for both, the enum
and the typedef
definition:
enum Tristate : char { Yes, No, Maybe };
typedef enum Tristate : char Tristate;
Otherwise you will get a compiler warning.
Or you define an anonymous enum
and typedef
directly:
typdef enum : char { Yes, No, Maybe } Tristate;
精彩评论