简体   繁体   中英

__attribute__((packed)) on a struct with only 1 element

I am going through some legacy code developed by a super star no longer working with the firm. All through his code he has packed structs. However I see him doing this for structure members with only 1 element as well. I am not sure if there are any benefits for him doing things this way. Am I missing something?

Sample code:

struct A { 
    uint32_t a __attribute__((packed));
};

It depends on the target architecture, and it would mostly affect arrays. For a 32 bit architecture, your example will really have no effect. On the other hand, for a 64 bit architecture, without the packed attribute the compiler might align entries in an array of struct A to 64 bits, leaving a 32 bit gap between each entry.

Unless you're facing serious memory constraints, it's a probably a bad idea.

Eric Raymond's "The Lost Art of C Structure Packing" is a very worthwile read on this topic.

according to gcc's documentation __attribute__ ((packed)) specifies that a structure field should have the smallest possible alignment.

so for a struct with only one field using it or not using it should not make any difference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM