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.

20 minfree previewLinux 6.12C11U-Boot 2025.x→ module 6 lab
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:

  1. Layer 1 — Pure Silicon Register Definitions (include/soc_regs.h): Owns immutable i.MX6ULL base addresses and _Static_assert-verified overlays (struct bsp_ccm_regs with _pad0[26] placing CCGR[0..6] at exact offsets +0x68..+0x80, sizeof == 0x84 = 132 B). Zero board pin numbers live here!
  2. Layer 2 — Narrow Subsystem Modules (bsp/clk/, bsp/led/, bsp/delay/): Each subsystem .c file includes soc_regs.h privately and owns one hardware domain (clk.c owns CCM_CCGR0..6; led.c + led_board.h own GPIO1_IO03 muxing and active-low inversion; delay.c owns timing). Their public headers (led.h, delay.h) expose only logical actions (void led_set(bool on);)—never volatile register structs!
  3. Layer 3 — Application Policy (project/start.S, project/main.c): Includes only led.h and delay.h. Consequently, as bsp_header_dep_audit.c proves, editing include/soc_regs.h rebuilds clk.o and led.o (0x13 with bsp.elf) while leaving project/main.o completely untouched!
fig_m06_l01_a.svg — Three-layer bare-metal BSP header firewall — main.c…

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:

ast_m06_l01.svg — Pair narrow subsystem headers with path-preserving…step 1/4
  1. Step 1. Step 1: Keep project/main.c purely logical (led_set, delay_ms) with zero raw literals.
  2. Step 2. Step 2: Encapsulate CCGR gates, pads, and active-low polarity inside bsp/clk, bsp/led, and bsp/delay.
  3. Step 3. Step 3: Mirror source paths under obj/ (obj/%.o: %.c) and list bsp.lds as a prerequisite of bsp.elf.
  4. 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:

  1. Preventing basename collisions (obj/init.o): Many tutorials flatten objects with OBJ := $(addprefix obj/,$(notdir $(SRC:.c=.o))). The moment both bsp/clk/init.c and bsp/led/init.c exist, both map to obj/init.o—silently overwriting one module at build time! Using $(patsubst %.c,obj/%.o,$(SRC)) with @mkdir -p $(dir $@) inside obj/%.o: %.c preserves a 1-to-1 bijection (obj/bsp/clk/init.o != obj/bsp/led/init.o).
  2. Why -MMD needs BOTH -MP and -include: Generating .d files without -include $(OBJ:.o=.d) does nothing at all! Leading - in -include tells Make not to fail on a clean checkout before .d files exist. Once .d files exist, if you refactor and delete led_board.h, Make sees obj/bsp/led/led.o: ... bsp/led/led_board.h in the old .d file and aborts with No rule to make target 'bsp/led/led_board.h' unless -MP emitted the empty phony target bsp/led/led_board.h:!
  3. Linker script & unified freestanding EABI flags: Notice bsp.elf: $(OBJ) bsp.lds—making bsp.lds a prerequisite forces a relink whenever VMA/LMA addresses change—and notice -ffreestanding -fno-builtin -mcpu=cortex-a7 -marm -mfloat-abi=soft shared across every .c and .S rule even when invoking an arm-linux-gnueabihf- toolchain prefix, preventing accidental VFP register usage before CPACR enables the FPU!
fig_m06_l01_b.svg — Path-mirroring pattern rules prevent basename…

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 PatternHeader Edit BehaviorHeader Rename / DeleteEngineering Verdict
-MMD -MP + -include $(OBJ:.o=.d)Rebuilds exact consumer .o set + bsp.elfSurvives cleanly via empty phony hdr.h: ruleProduction GNU Make standard
-MMD without -MPRebuilds exact consumer .o setFails with No rule to make target deleted.hBreaks refactoring without make clean
%.o: %.c with no .d includeRebuilds 0 objects on .h edits!Links stale struct offsets/macros into bsp.binDangerous silent build corruption
Flattened obj/$(notdir).oCollides whenever two folders have init.cOverwrites .o / .d files unpredictablyBroken on multi-subsystem BSPs
learner@ksa: ~/gl-e01/m06-l01
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
  1. Enforce one freestanding Cortex-A7 soft-float ABI across all objects and emit .d files with -MMD -MP.
  2. Mirror source paths under obj/ and create parent directories on demand via $(dir $@).
  3. Declare bsp.lds as an explicit prerequisite of bsp.elf so layout edits force a relink.
  4. 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
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;    }
  1. Verify sparse CCM CCGR0..CCGR6 (+0x68..+0x80) and GPIO (+0x00..+0x1C) BSP header offsets at compile time.
  2. Keep project/main.o decoupled from include/soc_regs.h so silicon-header edits rebuild only BSP driver objects.
  3. 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-l01
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-l01
strace — learner@ksa: ~/gl-e01/m06-l01
learner@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.

quiz · 1 of 3

An engineer updates a register offset inside include/soc_regs.h and runs make, but obj/bsp/clk/clk.o does not recompile. What is the first build-graph defect to check?

quiz · 2 of 3

Why does OBJ := $(patsubst %.c,obj/%.o,$(SRC)) mirror full relative paths (obj/bsp/clk/clk.o) instead of flattening every object into obj/$(notdir).o?

quiz · 3 of 3

Retrieval: why must bsp.lds appear in the prerequisite list of bsp.elf: $(OBJ) bsp.lds in addition to -Wl,-T,bsp.lds in the recipe?

Key takeaways

  • A modular BSP separates 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/%.o rules rather than directory conventions.
  • GCC/Clang -MMD emits non-system header dependencies per .o, while -MP adds empty phony header targets so deleted or renamed headers never stall incremental builds.
  • -include $(OBJ:.o=.d) reconnects .d files into Make's DAG, and bsp.elf: $(OBJ) bsp.lds ensures 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.
Progress is saved on this device.

search — fzf

0/0 ───────────────────────────────────────────

keyboard shortcuts — less

/
search
f
focus mode
[
previous
]
next
?
help
Esc
close

figure