Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Though __attribute__ ((aligned)) works well with the typedef declaration such as :

typedef struct __attribute__((__aligned__(8))) A {

     xxx ip    ;
     xxx udp   ;
     xxx ports ;
} table ;

I have come across statements which 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.

Now , In our code we define

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

Does the above declaration makes the compiler to silently dump the packed attribute declaration?

PS : Yes , I could have verified it ,but my circumstances are different at the moment .Lets say holidays and a smartphone !

like image 966
Borrito Avatar asked Aug 31 '12 10:08

Borrito


3 Answers

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", sizeof(NCO));
} 

or

#include <stdio.h> 

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

int main(void)
{
    printf("%zu", 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 .

like image 192
user1471 Avatar answered Nov 20 '22 19:11

user1471


Your declaration seems to be all right, but it is compiler-depended. For example if you want to make MinGW compiler respect it, you must compile your program with -mno-ms-bitfields parameter. If you don't specify this flag, no warning is issued, but the attribute is not honored!

like image 39
klasyc Avatar answered Nov 20 '22 20:11

klasyc


You are combining two statements here.

At first you define a struct with certain properties. Then you create an alias for it.

As you assign the packed-property to the alias, a already created data structure used by this alias won't be altered. (Usually you can create variables with "struct bla" and "s_bla" [created by "typedef struct bla {} s_bla"] and exchange these values among each other. If it would be possible to alter the struct by using typedef, this coherence will break.)

So: The declaration will be dumped.

like image 30
Nippey Avatar answered Nov 20 '22 21:11

Nippey