This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: C Struct inheritance?


After mailing the list, I showed a co-worker my post, and he spent all of 15 minutes tracking it down. MS extensions call it "Anonymous Structs":
http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx


GCC has a -fms-extensions option, which does then allow this behavior. Hurray! It appears to give me what I need for now.

-Kai Meyer

On 06/17/2011 10:33 AM, Kai Meyer wrote:
I'm basically straight out of acadamia with a 4 year CS degree, so be gentle :)

I've been working adding a Linux port to a current Windows-only project, and I've run into what appears to be inheritance with C structs. I've distilled the problem down to the following code:

// Test for struct inheritance
#ifdef __cplusplus
struct base
#else
typedef struct _base
#endif
{
int b;
#ifdef __cplusplus
};
#else
} base;
#endif
#ifdef __cplusplus
struct derived : public base
{
#else
typedef struct _derived
{
base;
#endif
int d;
#ifdef __cplusplus
};
#else
} derived;
#endif
int main()
{
base b;
derived d;
b.b = 5;
d.b = b.b;
d.d = 10;
return 0;
}

It is apparent that the struct is to behave the same whether compiled in C or C++. I admit to being a bit confused to see Polymorphism in C. This code builds and runs in my WinDDK environment for windows, as well as for Linux g++, but Linux gcc gives me the following error:
struct_test.c:20: warning: declaration does not declare anything
struct_test.c: In function ‘main’:
struct_test.c:33: error: ‘derived’ has no member named ‘b’


That totally makes sense. The C I know doesn't have polymorphism.

So, I need to derive a solution that will be cross-platform, and hopefully not require any changes to existing code that uses these structs. I'm sort of holding my breath for a gcc option like "-magic_structs". Any help or general advice is welcome.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]