Skip to content

Packing Structs

May 14, 2012

I’ve been sidetracked a bit of late looking at porting newlib (newlib is a standard C library – implementing it provides many useful functions and opens the possibility of porting GNU software). One little potential pitfall arose as a result of this.

By default gcc aligns the elements of structs to provide best performance. Depending upon the layout of the variables in the struct, this may lead to some empty padding bytes being inserted between variables (with the result that sizeof(struct x) will give a different result to adding the sizes of the elements of the struct). Previously I had been using the -fpack-structs flag to ensure that there were no such gaps, but this lead to problems with newlib, so I removed the flag. And then the compiled system would not run.

The reason is that some structs need to be packed; examples are the structs that represent the physical layout of disk structures, such as the MBR, partition tables, boot sectors, and directory entries. The simple solution is to add “__attribute__((packed))” at the end of the struct definition:

struct
{
}__attribute__((packed));

I have done this so now structs are not packed by default, but particular structs – that need to be – are. I have also rearranged the order of variables in most structs to put the longer ones first and the shorter ones last (although this, obviously, can’t be done with the previously mentioned disk structures). This reduces, or even eliminates, the need for padding bytes.

I’ll post more details about the implementation of newlib in a while. At the same time I’ll update github with the new code.

Advertisements

From → IanOS

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: