extern(C) enum

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Sep 15 18:20:06 UTC 2017


On Friday, September 15, 2017 15:35:48 bitwise via Digitalmars-d-learn 
wrote:
> On Friday, 15 September 2017 at 07:24:34 UTC, Jonathan M Davis
>
> wrote:
> > On Friday, September 15, 2017 04:15:57 bitwise via
> >
> > Digitalmars-d-learn wrote:
> >> I translated the headers for FreeType2 to D, and in many
> >> cases, enums are used as struct members.
> >>
> >> If I declare an extern(C) enum in D, is it guaranteed to have
> >> the same underlying type and size as it would for a C compiler
> >> on the same platform?
> >
> > extern(C) should have no effect on enums. It's for function
> > linkage, and enums don't even have an address, so they don't
> > actually end up in the program as a symbol. And since C's int
> > and D's int are the same on all platforms that D supports (we'd
> > have c_int otherwise, like we have c_long), any enum with a
> > base type of int (which is the default) will match what's in C.
> >
> > - Jonathan M Davis
>
> I'm confused...is it only C++ that has implementation defined
> enum size? I thought that was C as well.

It is my understanding that for both C and C++, an enum is always an int
(unless you're talking about enum classes in C++). The size of an int can
change based on your architecture, but AFAIK, all of the architectures
supported by D guarantee it it be 32 bits in C/C++ (certainly, all of the
architectures supported by dmd do), and druntime would have serious issues
if it were otherwise, as it assumes all of the place that D's int is the
same as C/C++'s int.

It's certainly possible that my understanding of C/C++ enums is wrong, but
if it is, you'd basically be screwed when dealing with any C functions that
take an enum in any case that an enum wasn't 32 bits - especially if the
C/C++ compiler could choose whatever size it wanted that fit the values.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list