How can I use “sizeof” in a preprocessor macro?

There are several ways of doing this.
Following snippets will produce no code if sizeof(someThing) equals PAGE_SIZE; otherwise they will produce a compile-time error.

1. C11 way

Starting with C11 you can use static_assert (requires #include <assert.h>).

Usage:

static_assert(sizeof(someThing) == PAGE_SIZE, "Data structure doesn't match page size");

2. Custom macro

If you just want to get a compile-time error when sizeof(something) is not what you expect, you can use following macro:

#define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))

Usage:

BUILD_BUG_ON( sizeof(someThing) != PAGE_SIZE );

This article explains in details why it works.

3. MS-specific

On Microsoft C++ compiler you can use C_ASSERT macro (requires #include <windows.h>), which uses a trick similar to the one described in section 2.

Usage:

C_ASSERT(sizeof(someThing) == PAGE_SIZE);

Leave a Comment