Modular BSP Layout and Dependency-Correct Make Rules
Architect a clean three-layer bare-metal Board Support Package (silicon headers, narrow subsystem drivers, and logical application code) backed by path-preserving GNU Make pattern rules and GCC -MMD -MP header dependency graphs.
What you'll learn
- Partition clock, indicator, delay, and application responsibilities into narrow modules.
- Write pattern rules that retain source paths and generate header dependencies.
- Diagnose a stale object caused by a missing header dependency.
Why Moving Files Into Folders Is Not Modularity Without a Header Firewall
Once a bare-metal codebase grows beyond start.S and one main.c into clock gating, status LEDs, buzzers, keys, UARTs, and timers, two failure modes hit almost every team simultaneously. First, engineers split .c files into neat bsp/clk/, bsp/led/, and project/ folders—but create a single giant "bsp_all.h" included everywhere, leaking 0x0209C000, IOMUXC hex constants, and active-low inversions straight into main.c! Second, an engineer edits a register offset or polarity macro inside a .h file, runs make, flashes bsp.bin, and wastes two hours debugging hardware because make saw no .c timestamp change and silently linked yesterday's stale .o file!
Study Figure 6.1a to see how a real production Board Support Package (BSP) establishes both architectural information hiding and minimal incremental rebuild blast radius:
- Layer 1 — Pure Silicon Register Definitions (
include/soc_regs.h): Owns immutablei.MX6ULLbase addresses and_Static_assert-verified overlays (struct bsp_ccm_regswith_pad0[26]placingCCGR[0..6]at exact offsets+0x68..+0x80,sizeof == 0x84 = 132 B). Zero board pin numbers live here! - Layer 2 — Narrow Subsystem Modules (
bsp/clk/,bsp/led/,bsp/delay/): Each subsystem.cfile includessoc_regs.hprivately and owns one hardware domain (clk.cownsCCM_CCGR0..6;led.c+led_board.hownGPIO1_IO03muxing and active-low inversion;delay.cowns timing). Their public headers (led.h,delay.h) expose only logical actions (void led_set(bool on);)—nevervolatileregister structs! - Layer 3 — Application Policy (
project/start.S,project/main.c): Includes onlyled.handdelay.h. Consequently, asbsp_header_dep_audit.cproves, editinginclude/soc_regs.hrebuildsclk.oandled.o(0x13withbsp.elf) while leavingproject/main.ocompletely untouched!
Figure 6.1a. Three-layer bare-metal BSP header firewall — main.c never sees soc_regs.h, bounding both coupling and incremental rebuilds.
mental model: A modular BSP and its Makefile work like a multi-sheet electrical schematic paired with an automated netlist checker: neat sheet boundaries isolate raw peripheral stages (soc_regs.h) from control logic (main.c), while the netlist (-MMD -MP .d files) ensures changing one header constant flags every affected .o target automatically.
Where it stops working: Unlike visual folder trees in an editor, GNU Make knows nothing about directories unless explicit pattern rules mirror paths under obj/ and -include splices generated .d prerequisite edges into the DAG.
definition (Modular BSP Ownership & GCC -MMD -MP Dependency Generation): A modular Board Support Package (BSP) partitions clock, indicator, timing, and application code behind narrow public headers while GNU Make schedules rebuilds strictly from its declared Directed Acyclic Graph (DAG) of target prerequisites—never from folder layout. Passing -MMD tells GCC/Clang to emit a .d file listing every non-system #include consumed by that .o, -MP appends empty phony header.h: rules so renamed or deleted headers do not break make, and -include $(OBJ:.o=.d) splices those edges into subsequent incremental builds.
Step through the four-stage ownership and dependency loop below:
- Step 1. Step 1: Keep project/main.c purely logical (led_set, delay_ms) with zero raw literals.
- Step 2. Step 2: Encapsulate CCGR gates, pads, and active-low polarity inside bsp/clk, bsp/led, and bsp/delay.
- Step 3. Step 3: Mirror source paths under obj/ (obj/%.o: %.c) and list bsp.lds as a prerequisite of bsp.elf.
- Step 4. Step 4: Compile with -MMD -MP and load -include $(OBJ:.o=.d) so header edits rebuild exact consumer .o files.
Figure 6.1b. Pair narrow subsystem headers with path-preserving obj/%.o rules and -include $(OBJ:.o=.d) so neither object collisions nor stale headers can survive.
Path-Preserving Object Rules, Phony Header Guards & ABI Consistency
Inspect Figure 6.1b alongside Makefile (target_m06_l01) below to see three subtle Makefile bugs prevented by 15 clean lines:
- Preventing basename collisions (
obj/init.o): Many tutorials flatten objects withOBJ := $(addprefix obj/,$(notdir $(SRC:.c=.o))). The moment bothbsp/clk/init.candbsp/led/init.cexist, both map toobj/init.o—silently overwriting one module at build time! Using$(patsubst %.c,obj/%.o,$(SRC))with@mkdir -p $(dir $@)insideobj/%.o: %.cpreserves a 1-to-1 bijection (obj/bsp/clk/init.o != obj/bsp/led/init.o). - Why
-MMDneeds BOTH-MPand-include: Generating.dfiles without-include $(OBJ:.o=.d)does nothing at all! Leading-in-includetells Make not to fail on a clean checkout before.dfiles exist. Once.dfiles exist, if you refactor and deleteled_board.h, Make seesobj/bsp/led/led.o: ... bsp/led/led_board.hin the old.dfile and aborts withNo rule to make target 'bsp/led/led_board.h'unless-MPemitted the empty phony targetbsp/led/led_board.h:! - Linker script & unified freestanding
EABIflags: Noticebsp.elf: $(OBJ) bsp.lds—makingbsp.ldsa prerequisite forces a relink wheneverVMA/LMAaddresses change—and notice-ffreestanding -fno-builtin -mcpu=cortex-a7 -marm -mfloat-abi=softshared across every.cand.Srule even when invoking anarm-linux-gnueabihf-toolchain prefix, preventing accidental VFP register usage beforeCPACRenables the FPU!
Figure 6.1b. Path-mirroring pattern rules prevent basename collisions (left), while -MMD -MP plus -include closes the incremental header rebuild DAG (right).
| Makefile / Header Pattern | Header Edit Behavior | Header Rename / Delete | Engineering Verdict |
|---|---|---|---|
-MMD -MP + -include $(OBJ:.o=.d) | Rebuilds exact consumer .o set + bsp.elf | Survives cleanly via empty phony hdr.h: rule | Production GNU Make standard |
-MMD without -MP | Rebuilds exact consumer .o set | Fails with No rule to make target deleted.h | Breaks refactoring without make clean |
%.o: %.c with no .d include | Rebuilds 0 objects on .h edits! | Links stale struct offsets/macros into bsp.bin | Dangerous silent build corruption |
Flattened obj/$(notdir).o | Collides whenever two folders have init.c | Overwrites .o / .d files unpredictably | Broken on multi-subsystem BSPs |
learner@ksa:~/gl-e01/m06-l01$ bat -H 4 -H 5 -H 8 -H 10 -H 11 -H 12 -H 16 -H 20 Makefile File: Makefile CROSS_COMPILE ?= arm-linux-gnueabihf- CC := $(CROSS_COMPILE)gcc OBJCOPY := $(CROSS_COMPILE)objcopy CFLAGS := -std=c11 -Wall -Wextra -Werror -O2 -ffreestanding \ -fno-builtin -mcpu=cortex-a7 -marm -mfloat-abi=soft -MMD -MP CPPFLAGS := -Iinclude -Ibsp/clk -Ibsp/led -Ibsp/delay SRC := project/main.c bsp/clk/clk.c bsp/led/led.c bsp/delay/delay.c OBJ := $(patsubst %.c,obj/%.o,$(SRC)) obj/project/start.o all: bsp.bin obj/%.o: %.c @mkdir -p $(dir $@) $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@ obj/%.o: %.S @mkdir -p $(dir $@) $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@ bsp.elf: $(OBJ) bsp.lds $(CC) -nostdlib -Wl,-T,bsp.lds,-Map,bsp.map $(OBJ) -o $@ bsp.bin: bsp.elf $(OBJCOPY) -O binary $< $@ -include $(OBJ:.o=.d) .PHONY: all- Enforce one freestanding Cortex-A7 soft-float ABI across all objects and emit .d files with -MMD -MP.
- Mirror source paths under obj/ and create parent directories on demand via $(dir $@).
- Declare bsp.lds as an explicit prerequisite of bsp.elf so layout edits force a relink.
- Splice generated .d files into Make's DAG, tolerating missing .d files on the initial clean build.
Auditing CCM Sparse Struct Offsets & DAG Invalidation Closure in C11
In bsp_header_dep_audit.c below, we prove two properties side by side: first, _Static_assert verifies struct bsp_ccm_regs (26 reserved uint32_t words = 0x68 bytes ahead of CCGR[7], placing CCGR[0] at +0x68, CCGR[1] at +0x6C, CCGR[6] at +0x80, and sizeof == 0x84 = 132 B); second, invalid_targets(changed) computes the exact bitmask of invalidated targets when soc_regs.h (0x13 = clk.o | led.o | bsp.elf), led_board.h (0x12 = led.o | bsp.elf), led.h (0x1A = led.o | main.o | bsp.elf), or bsp.lds (0x10 = bsp.elf only) is modified!
learner@ksa:~/gl-e01/m06-l01$ bat -H 8 -H 9 -H 10 -H 11 -H 12 -H 13 -H 14 -H 15 -H 16 -H 22 -H 23 -H 24 -H 25 -H 26 -H 27 -H 28 -H 29 -H 30 -H 31 -H 32 -H 33 -H 34 -H 35 bsp_header_dep_audit.c File: bsp_header_dep_audit.c #include <assert.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <string.h> struct bsp_ccm_regs { volatile uint32_t _pad0[26]; /* 0x00..0x64 */ volatile uint32_t CCGR[7]; /* 0x68..0x80 */ }; _Static_assert(offsetof(struct bsp_ccm_regs, CCGR[0]) == 0x68U, "CCGR0"); _Static_assert(offsetof(struct bsp_ccm_regs, CCGR[1]) == 0x6cU, "CCGR1"); _Static_assert(offsetof(struct bsp_ccm_regs, CCGR[6]) == 0x80U, "CCGR6"); _Static_assert(sizeof(struct bsp_ccm_regs) == 0x84U, "CCM span"); enum inputs { IN_SOC_REGS = 1U, IN_LED_BRD = 2U, IN_LED_API = 4U, IN_DELAY_API = 8U, IN_LDS = 16U }; enum targets { T_CLK_O = 1U, T_LED_O = 2U, T_DLY_O = 4U, T_MAIN_O = 8U, T_ELF = 16U }; static unsigned invalid_targets(unsigned changed) { const unsigned obj_deps[4] = { IN_SOC_REGS, /* obj/bsp/clk/clk.o */ IN_SOC_REGS | IN_LED_BRD | IN_LED_API, /* obj/bsp/led/led.o */ IN_DELAY_API, /* obj/bsp/delay/delay.o */ IN_LED_API | IN_DELAY_API /* obj/project/main.o */ }; unsigned out = 0U; for (size_t i = 0U; i < 4U; ++i) if ((obj_deps[i] & changed) != 0U) out |= (1U << i); if (out != 0U || (changed & IN_LDS) != 0U) out |= T_ELF; return out; } int main(void) { assert(invalid_targets(0U) == 0U); assert(invalid_targets(IN_SOC_REGS) == (T_CLK_O | T_LED_O | T_ELF)); assert(invalid_targets(IN_LED_BRD) == (T_LED_O | T_ELF)); assert(invalid_targets(IN_LED_API) == (T_LED_O | T_MAIN_O | T_ELF)); assert(invalid_targets(IN_LDS) == T_ELF); assert(strcmp("obj/bsp/clk/init.o", "obj/bsp/led/init.o") != 0); printf("CCM_span=%zuB CCGR1=+0x%02zX soc_chg=0x%02X brd_chg=0x%02X lds_chg=0x%02X\n", sizeof(struct bsp_ccm_regs), offsetof(struct bsp_ccm_regs, CCGR[1]), invalid_targets(IN_SOC_REGS), invalid_targets(IN_LED_BRD), invalid_targets(IN_LDS)); return 0; }- Verify sparse CCM CCGR0..CCGR6 (+0x68..+0x80) and GPIO (+0x00..+0x1C) BSP header offsets at compile time.
- Keep project/main.o decoupled from include/soc_regs.h so silicon-header edits rebuild only BSP driver objects.
- Propagate any rebuilt .o or modified bsp.lds prerequisite into a relink of bsp.elf (bit 4).
Compiling with -MMD -MP & Verifying Incremental Invalidation Masks
Compile bsp_header_dep_audit.c with -MMD -MP and execute the audit binary below. Confirm CCM_span=132B, CCGR1=+0x6C, soc_chg=0x13, brd_chg=0x12, and lds_chg=0x10.
learner@ksa:~/gl-e01/m06-l01gcc -std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP bsp_header_dep_audit.c -o bsp_header_dep_auditlearner@ksa:~/gl-e01/m06-l01./bsp_header_dep_auditCCM_span=132B CCGR1=+0x6C soc_chg=0x13 brd_chg=0x12 lds_chg=0x10learner@ksa:~/gl-e01/m06-l01learner@ksa:~/gl-e01/m06-l01strace -e trace=write,exit_group \./bsp_header_dep_auditwrite(1, "CCM_span=132B CCGR1=+0x6C soc_ch"..., 65) = 65exit_group(0) = ?+++ exited with 0 +++Tracking Compiler Flag Changes Alongside Header Dependencies
One subtle detail separates good Makefiles from airtight ones: .d files track .c and .h timestamps, not edits to CFLAGS inside Makefile! If you switch -mfloat-abi=hard to -mfloat-abi=soft inside Makefile without running make clean, existing obj/*.o files appear "up to date" and fail at link time with a VFP ABI mismatch. Listing Makefile as a second prerequisite on pattern rules (obj/%.o: %.c Makefile, keeping $< bound to the first prerequisite %.c!) automatically invalidates all objects whenever compiler flags change. Later: Lesson m06-l02 adds a new actuator subsystem (bsp/buzzer/) to this modular BSP, deriving PNP vs NPN transistor switching circuits and SNVS GPIO5 clock gating from first principles.
Common Production Pitfalls
warning: Symptom: Editing LED_PIN inside bsp/led/led_board.h and running make prints Nothing to be done for 'all', leaving the old pin number baked into bsp.bin. Root Cause: Either -MMD -MP was omitted from CFLAGS, or -include looked for *.d in the project root while objects (and .d files) were placed under obj/bsp/led/led.d. Fix: Match the -include glob directly to OBJ via -include $(OBJ:.o=.d) and verify with touch bsp/led/led_board.h && make -n.
warning: Symptom: Changing -mfloat-abi=hard to -mfloat-abi=soft in Makefile and running incremental make fails during ld with uses VFP register arguments, bsp.elf does not. Root Cause: Generated .d files record #include header files, not Makefile flag variables, leaving stale hard-float .o files on disk. Fix: Add Makefile (or a compiler-flags stamp file) as a prerequisite on obj/%.o: %.c Makefile or run a clean rebuild whenever ABI flags change.
Practice & Retrieval
Guided Practice: Tracing a Deleted Header & Linker-Script Edit
Walk through two incremental build scenarios. Step 1 (Deleted Header): Suppose obj/bsp/led/led.d lists bsp/led/old_pins.h without -MP and you merge old_pins.h into led_board.h and delete old_pins.h: Make aborts with No rule to make target 'bsp/led/old_pins.h', whereas -MP's empty bsp/led/old_pins.h: rule lets led.o recompile and regenerate a clean led.d. Step 2 (Linker Edit): Touching bsp.lds alone triggers bsp.elf -> bsp.bin with zero .c recompilations (lds_chg=0x10).
Independent Practice: Build-Graph Layer & Cycle Linter (build_graph_lint.c)
Extend bsp_header_dep_audit.c into build_graph_lint.c that checks an array of source paths for flattened $(notdir) collisions, flags architectural layer violations if project/* includes include/soc_regs.h directly, and detects circular #include cycles via 3-color depth-first search.
Key takeaways
- A modular
BSPseparates pure silicon register structs (include/soc_regs.h), board-aware subsystem drivers (bsp/clk/,bsp/led/,bsp/delay/), and logical application code (project/main.c). - GNU Make rebuilds targets strictly from declared prerequisite timestamps and path-preserving
obj/%.orules rather than directory conventions. GCC/Clang-MMDemits non-system header dependencies per.o, while-MPadds empty phony header targets so deleted or renamed headers never stall incremental builds.-include $(OBJ:.o=.d)reconnects.dfiles into Make'sDAG, andbsp.elf: $(OBJ) bsp.ldsensures linker-script edits trigger deterministic relinking.- A can separate clock, LED, delay, and application responsibilities into distinct source modules.
- GNU Make decides rebuilds from declared prerequisites and artifact state rather than directory appearance.
- A new link of the that depends on that placement policy.