C cpp patterns

From j4flmao/agent-skills · View interactive version

C cpp patterns is an AI agent skill from the GitHub repository j4flmao/agent-skills. Use when the user asks about embedded C or C++ firmware, register access, volatile, memory-mapped IO, ISR data sharing, ring buffers, struct packing, MISRA or linker scripts. Produces microcontroller C/C++ with static memory and safe register access. Not for RTOS task design (use rtos) or desktop C+

How to use this skill

Skill file

Embedded C/C++ Patterns

Purpose

Firmware bugs come from a short list: wrong register access, data shared with ISRs unsafely, heap fragmentation, undefined behaviour the optimiser exploits, and layout assumptions. This skill gives the patterns that avoid them in C (C11/C17) and in a restricted C++ (C++17/20 without exceptions/RTTI/heap) suitable for MCUs.

Agent Protocol

Trigger

"embedded C", "embedded C++", "firmware", "register access", "volatile", "memory-mapped IO", "ISR", "ring buffer", "struct packing", "alignment", "MISRA", "linker script".

Input Context

Output Artifact

C/C++ code, review findings, or build flags. No file unless requested.

Response Format

Target: {MCU, toolchain, -std}
Pattern: {name}
Code: {snippet}
Concurrency: {what can interrupt this and how it is protected}
Checks: {static analysis / MISRA rules touched}

1. Register Access

#define GPIOA_ODR (*(volatile uint32_t *)0x40020014u)   /* STM32F4 example */

2. Sharing Data Between ISR and Main

static volatile uint32_t g_ticks;              /* written in ISR, read in main */

void SysTick_Handler(void) { g_ticks++; }      /* 32-bit aligned store: atomic on Cortex-M */

uint32_t ticks_now(void) { return g_ticks; }   /* single aligned 32-bit read is atomic */

/* Multi-word or read-modify-write: short critical section */
static inline uint32_t irq_save(void) { uint32_t p = __get_PRIMASK(); __disable_irq(); return p; }
static inline void irq_restore(uint32_t p) { __set_PRIMASK(p); }

Lock-free single-producer/single-consumer ring buffer

#define RB_SIZE 256u                            /* power of two */
typedef struct {
    uint8_t buf[RB_SIZE];
    volatile uint32_t head;                     /* written only by producer (ISR) */
    volatile uint32_t tail;                     /* written only by consumer (main) */
} ringbuf_t;

static bool rb_put(ringbuf_t *rb, uint8_t b)    /* ISR side */
{
    uint32_t h = rb->head;
    if ((h - rb->tail) == RB_SIZE) return false; /* full */
    rb->buf[h & (RB_SIZE - 1u)] = b;
    __DMB();                                     /* data visible before index */
    rb->head = h + 1u;
    return true;
}

static bool rb_get(ringbuf_t *rb, uint8_t *out) /* main side */
{
    uint32_t t = rb->tail;
    if (rb->head == t) return false;            /* empty */
    *out = rb->buf[t & (RB_SIZE - 1u)];
    __DMB();
    rb->tail = t + 1u;
    return true;
}

Free-running unsigned indices wrap correctly because RB_SIZE divides 2^32.

3. Memory Discipline

4. Types, Layout and Packing

5. Undefined Behaviour that Bites Firmware

| UB | Example | Fix |

|----|---------|-----|

| Signed overflow | int32_t t = a + b; near limits | unsigned arithmetic or checked add |

| Shift >= width | 1 << 32, 1 << 31 on int | 1u << n with n < 32 checked |

| Unsequenced modification | i = i++ + 1; | split statements |

| Null/misaligned deref | packed struct member pointers | memcpy |

| Infinite loop without side effects | while (!flag); with non-volatile flag | volatile / atomic flag |

Compile with -Wall -Wextra -Wconversion -Werror and run cppcheck (with MISRA addon), clang-tidy, or a commercial MISRA checker.

6. C++ on Microcontrollers

class CriticalSection {
public:
    CriticalSection() : primask_(__get_PRIMASK()) { __disable_irq(); }
    ~CriticalSection() { __set_PRIMASK(primask_); }
    CriticalSection(const CriticalSection&) = delete;
    CriticalSection& operator=(const CriticalSection&) = delete;
private:
    uint32_t primask_;
};

void enqueue(Event e) {
    CriticalSection cs;          // released on every return path
    queue.push(e);
}

7. Startup, Linker and Build

8. Anti-Patterns

9. Checklist

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.