Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 37 ยท Embedded C

Macros, Inline Functions and Compile-Time Checks

Write safe preprocessor macros, choose static inline functions, use enums, X-macros, conditional compilation and static_assert to catch embedded bugs at compile time.

The preprocessor is a text-substitution tool that runs before the compiler sees your code. In embedded C it has legitimate, important jobs: naming hardware addresses, selecting code for a particular board, building tables, and stripping debug code from a release build. It is also a famous source of subtle bugs. Modern C gives you safer tools for many of its old jobs: static inline functions, enum, const and static_assert.

This lesson shows which tool to pick when, how to write macros that do not bite, how to generate tables with the X-macro technique, and how to make the compiler check your assumptions about sizes and layouts before the program ever runs.

Object-like macros and the alternatives

C
#define SYSTEM_CLOCK_HZ   168000000u
#define LED_PIN           5u
#define BUFFER_SIZE       64u

These are fine for constants that must work in the preprocessor (#if) or in places that need a constant expression. But a macro has no type, no scope and no symbol in the debugger. Where possible prefer:

C
enum { BUFFER_SIZE = 64 };                       // integer constants, usable as array sizes
static const uint32_t system_clock_hz = 168000000u;   // typed, visible to the debugger

In C (not C++), a const variable is not a constant expression, so uint8_t buf[N]; with const int N = 64; is a variable-length array. Use enum or #define for array sizes.

Always parenthesize and use unsigned suffixes: #define TIMEOUT_MS (5u * 1000u).

Function-like macros: the traps

C
#define SQUARE(x)  x * x
int a = SQUARE(2 + 3);      // 2 + 3 * 2 + 3 = 11, not 25

Three rules prevent most trouble:

  1. Parenthesize every parameter and the whole expression: #define SQUARE(x) ((x) * (x)).
  2. Never pass arguments with side effects: SQUARE(i++) increments i twice.
  3. Wrap multi-statement macros in do { ... } while (0) so they behave like a single statement after an if without braces.
C Macro pitfalls, bad and good

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

static inline functions

A static inline function gives you what function-like macros promised: no call overhead (the compiler can paste the body in), plus type checking, single evaluation of arguments and debugger support. Put small helpers in headers as static inline.

C
static inline uint32_t bit(unsigned n)          { return 1u << n; }
static inline uint32_t clamp_u32(uint32_t v, uint32_t lo, uint32_t hi) {
    return v < lo ? lo : (v > hi ? hi : v);
}

Use macros only when you need things functions cannot do: stringification (#x), token pasting (a##b), generic code over types before C11 _Generic, __FILE__/__LINE__ capture, or conditional compilation. In C11 and later, _Generic lets you select an implementation by argument type.

Conditional compilation

Firmware supports many boards and build types from one code base:

C
#if defined(BOARD_NUCLEO_F446)
    #define LED_PIN   5
    #define LED_PORT  GPIOA
#elif defined(BOARD_PICO)
    #define LED_PIN   25
#else
    #error "Select a board: define BOARD_NUCLEO_F446 or BOARD_PICO"
#endif

#ifdef DEBUG
    #define LOG(...) printf(__VA_ARGS__)
#else
    #define LOG(...) ((void)0)
#endif

#error stops the build when a required setting is missing: better than a silent wrong default. A word of caution: the more #if branches, the more combinations you must test. Keep hardware differences in a small number of files (a "board support" header) rather than scattered everywhere.

C A debug log macro that disappears in release builds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Set #define DEBUG 0 and the logging calls compile to nothing: zero flash, zero time. That is the value of conditional compilation in a size-limited product.

X-macros: one list, many tables

When the same list of names must appear as an enum, a string table and a handler table, writing it three times invites mistakes: you add an item to one place and forget the others. An X-macro writes the list once and expands it with different definitions of X:

C
#define ERROR_LIST(X) \
    X(ERR_NONE,    "ok")        \
    X(ERR_TIMEOUT, "timeout")   \
    X(ERR_CRC,     "bad crc")   \
    X(ERR_BUSY,    "busy")
C X-macro: enum and string table from one list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Add a line to ERROR_LIST and both the enum and the table update. The same technique generates register dumps, command tables, and interrupt vector lists.

Compile-time checks with static_assert

A bug found by the compiler costs seconds; a bug found in the field costs a recall. static_assert(condition, "message") (from <assert.h> as static_assert in C11, a keyword in C23) fails the build when a condition about constants is false. Use it to lock down assumptions:

C
static_assert(sizeof(uint32_t) == 4, "uint32_t must be 4 bytes");
static_assert(sizeof(Packet) == 12, "Packet layout changed: protocol break!");
static_assert((BUFFER_SIZE & (BUFFER_SIZE - 1)) == 0, "BUFFER_SIZE must be a power of 2");
static_assert(sizeof(error_text) / sizeof(error_text[0]) == ERR_COUNT, "table out of sync");

The power-of-two check is typical: a ring buffer that wraps with index & (SIZE - 1) silently misbehaves for any other size. Offsets of a register struct are checked the same way, so the struct can never drift from the datasheet (Memory-Mapped Registers).

C static_assert guards layout assumptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Enums, _Generic and other helpers

  • enum gives named integer constants and groups them; declare states and error codes as enums and switch over them (compilers warn about missing cases with -Wswitch).
  • _Generic (C11) chooses an expression by type, useful for type-safe "generic" helpers without C++ templates.
  • __attribute__((unused)), __attribute__((noreturn)), __attribute__((section("..."))), __attribute__((aligned(n))) and __attribute__((weak)) are GCC/Clang extensions you will meet in vendor code. Weak functions let a library supply a default handler that your code can override.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does #define SQUARE(x) x * x return for SQUARE(2 + 3)?

    It expands to 2 + 3 * 2 + 3 = 11. Parenthesize the parameter and the result: ((x) * (x)).
  2. 2. Why wrap multi-statement macros in do { ... } while (0)?

    Without it, only the first statement belongs to the if and the others always run.
  3. 3. What is the main advantage of a static inline function over a function-like macro?

    Functions check types and evaluate each argument once, while the optimizer can still inline them.
  4. 4. What does static_assert do?

    It is evaluated by the compiler, so layout or configuration mistakes stop the build.

Summary

  • Prefer enum, const and static inline over macros; keep macros for conditional compilation, stringification and token pasting.
  • Parenthesize macro parameters, avoid side effects in arguments, and wrap statements in do { } while (0).
  • #if/#error select and validate board and build configurations; keep them in few files.
  • X-macros generate enums, name tables and handler tables from a single list.
  • static_assert turns assumptions (sizes, offsets, power-of-two buffers) into build failures.

Next: State Machines in C