Alex Rivera | Logout

Is __attribute__ ((__packed__)) ignored on a typedef declaration?

Asked 2012-08-31T10:52:21.713
26

Although __attribute__ ((aligned)) works well with the typedef declarations, such as

typedef struct __attribute__((__aligned__(8))) A {
     xxx ip    ;
     xxx udp   ;
     xxx ports ;
} table ;

I have come across statements that say that this is not the case with __attribute__ ((__packed__)) with typedef! I was going through some of the related question and some of them have used the packed attribute with typedef which tallies with our code.

In our code we define

typedef struct {
     xxx ip    ;
     xxx udp   ;
     xxx ports ;
} __attribute__((packed)) table ;

Does the above declaration make the compiler silently dump the packed attribute declaration?

Edit
Report

1 Answer

26

The declaration looks okay. However try to adhere to one of the following to avoid silent attribute discardation.

#include <stdio.h>

typedef struct __attribute__((packed)) {
    char old;
    int ip;
    int new;
} NCO;

int main(void)
{ 
    printf("%zu\n", sizeof(NCO));
} 

or

#include <stdio.h> 

typedef struct {
    char old;
    int ip;
    int new;
} __attribute__((packed)) NCO;

int main(void)
{
    printf("%zu\n", sizeof(NCO));
} 

Ensure that the __attribute__((packed)) keyword and attribute specification immediately follow the right brace (}) of the structure declaration. If it is in any other position (such as, following a structure instance instead of preceding a structure instance), the compiler shall ignore __attribute__((packed)) and issue a warning message.

Although it gives us the packed size 9 , I think it is better to avoid it as stated here and try the old school structure declaration style .

answered 2012-08-31T14:32:20.300

Your Answer