Skip to content
systemcoding.dev
Performance

Warn about struct padding with -Wpadded

Turn on -Wpadded in GCC 14 to list every struct that gets padding bytes, then reorder members from largest to smallest to shrink the type.

1 min read
Summarize in AI

Padding is invisible in the source, and -Wpadded makes the compiler say where it inserts some. GCC 14 warns for each hole inside a struct and for the tail padding added to reach the alignment.

pad.cc
#include <stdio.h>

struct Loose { char a; int b; char c; };
struct Tight { int b; char a; char c; };

int main(void) {
    printf("%zu %zu\n", sizeof(struct Loose), sizeof(struct Tight));
}
Text
pad.c:3:30: warning: padding struct to align 'b' [-Wpadded]
pad.c:3:42: warning: padding struct size to alignment boundary [-Wpadded]
pad.c:4:42: warning: padding struct size to alignment boundary [-Wpadded]
12 8

The exact columns differ, but Loose gets a hole before b and tail padding, and Tight only gets tail padding. Putting members in order of decreasing alignment moves 4 of the 12 bytes away. The flag is too noisy to leave on for a whole project, since every struct that is not perfectly packed is reported, including ones you do not control, so turn it on for one header at a time with -Wpadded on the command line of a single file. It does not warn about padding added by __attribute__((aligned)). See the GCC warning options.

Taggedcgcc
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.