Why does this c struct work?

180 Views Asked by At

I see flow c language code in the windows driver kit(WDK) sample:

typedef struct _COMMON_DEVICE_DATA
{
    PDEVICE_OBJECT  Self;

    BOOLEAN         IsFDO;
    ......................


} COMMON_DEVICE_DATA, *PCOMMON_DEVICE_DATA;


typedef struct _PDO_DEVICE_DATA
{
    COMMON_DEVICE_DATA;

    PDEVICE_OBJECT  ParentFdo;

    .................

} PDO_DEVICE_DATA, *PPDO_DEVICE_DATA;

But when I want to test the smillar code , it build error.

test.c:14:6: error: ‘AA’ has no member named ‘flag’
     a.flag = 1;

Tesing code as fllow:

typedef struct __COMMON_DATA{     
    int flag;
}COMMON_DATA;

typedef struct __AA{
    COMMON_DATA;
    int x;
    int y;
}AA;

int main(int argc, char *argv[])
{
    AA a;
    a.flag = 1;
    return 0;
}

All seem same as the window sample code, But where is it wrong?

3

There are 3 best solutions below

1
On

there is no member named flag because AA has no member named flag

typedef struct __AA{
    COMMON_DATA aa_flag;
    int x;
    int y;
}AA;

You should access actual flag in the COMMON_DATA struct not in AA struct

a.aa_flag.flag = 1;
4
On

The syntax used in the WDK code sample is a Microsoft extension for structure inheritance in C. But your error message looks like a gcc error message.

If you are actually using gcc, you could try building with -fms-extensions.

Link to related answer

0
On

If you've compile this with -Wall -Wextra -pedantic, you can see this warning before error:

./struct.c:6:16: warning: declaration does not declare anything
     COMMON_DATA;

It can be fixed with addition name of variable to code. This works fine:

typedef struct __COMMON_DATA{     
    int flag;
}COMMON_DATA;

typedef struct __AA{
    COMMON_DATA cd;
    int x;
    int y;
}AA;

int main(int argc, char *argv[])
{
    AA a;
    a.cd.flag = 1;
    return 0;
}