c-cpp-patterns
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…
by j4flmao★ 47 GitHub stars
Install c-cpp-patterns in Claude Code & Claude Desktop
Sign up to install this skill
Create a free account to reveal the install command and save the skill to your library.
- Reveal the one-line install command
- Save skills to your synced library
- Get notified when skills update
About this skill
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
- MCU/core and vendor SDK (CMSIS, STM32 HAL/LL, nRF SDK/Zephyr, ESP-IDF, Pico SDK)
- Toolchain (arm-none-eabi-gcc, Clang, IAR, Keil) and language standard
- Coding standard (MISRA C:2012/2023, AUTOSAR C++14, CERT C)
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
- Use the vendor CMSIS device header (
stm32f4xx.h,nrf52840.h): it defines peripheral structs withvolatilemembers (__IO) at the right addresses. Hand-written addresses only when no header exists:
#define GPIOA_ODR (*(volatile uint32_t *)0x40020014u) /* STM32F4 example */
- Read-modify-write of a register is not atomic. If an ISR touches the same register, protect it or use set/reset registers (
GPIOx->BSRR = (1u << pin);sets atomically). volatileprevents the compiler from caching or eliding accesses; it gives no atomicity and no ordering versus other memory. For DMA buffers add__DMB()/ cache maintenance (SCB_CleanDCache_by_Addr) on cores with D-cache (Cortex-M7).
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); }
- Prefer C11
<stdatomic.h>(atomic_fetch_add_explicit) on cores with LDREX/STREX (Cortex-M3 and up); Cortex-M0/M0+ has no exclusive access — use critical sections. - Save/restore PRIMASK rather than blindly re-enabling interrupts, so nested critical sections work.
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
- No
malloc/freeafter init (MISRA C:2012 Rule 21.3). Use static arrays, fixed-block pools, or allocate once at startup. - Put large buffers in
staticstorage, not on the stack; measure stack with a fill pattern or-fstack-usage+ call-graph analysis. - Place data explicitly with sections when needed:
__attribute__((section(".dtcm")))for tightly coupled RAM, DMA-capable RAM regions on parts where not all RAM is DMA-reachable.
4. Types, Layout and Packing
- Use
<stdint.h>fixed-width types; never assumeintis 32 bits on 8/16-bit parts. - Structs get padding so members are naturally aligned; order members largest-first to minimise padding;
_Static_assert(sizeof(hdr_t) == 12, "wire layout");. - Do not overlay packed structs on wire buffers and dereference members:
__attribute__((packed))member access can be unaligned (faults on Cortex-M0, slow elsewhere) and endianness is host-dependent. Serialise with explicit byte shifts ormemcpy. - Bit-fields have implementation-defined layout — never use them to model registers or wire formats portably.
- Type punning: use
memcpy(optimised away) — castingfloat*touint32_t*violates strict aliasing.
5. Undefined Behaviour that Bites Firmware
| UB | Example | Fix |
|---|---|---|
| Signed overflow | int32_t t = a + b; near limits |
Allowed tools
Tools this skill is permitted to call.
No restriction — this skill can use any tool.
FAQ
What does the c-cpp-patterns skill do?
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++ (use lang-cpp).
How do I install the c-cpp-patterns skill?
Copy the skill folder into ~/.claude/skills (the Claude Code tab above does this in one command), or install it as a plugin.
Does the c-cpp-patterns skill run scripts?
No, this skill is instructions only (SKILL.md) with no executable scripts.
Related skills
skill-creator
AnthropicCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
discernment-nudge
AnthropicAfter you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
data-consolidate
AnthropicJoins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
inspection-to-capa
AnthropicRuns the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…