How do you build an out-of-tree kernel module?
Short answer: Write a minimal Kbuild Makefile that sets obj-m and calls the kernel build system with M=$(PWD). Build against the configured source or headers of the exact kernel the module will run on (vermagic must match). For an embedded target, point KDIR at the target kernel build tree and pass ARCH and CROSS_COMPILE.
obj-m += mydrv.o
mydrv-y := main.o hw.o # module built from several files
KDIR ?= /lib/modules/$(shell uname -r)/build
all:
$(MAKE) -C $(KDIR) M=$(PWD) modules
clean:
$(MAKE) -C $(KDIR) M=$(PWD) clean
install:
$(MAKE) -C $(KDIR) M=$(PWD) modules_install
Cross-compiling for an ARM64 board
make KDIR=~/linux-build ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu-
The KDIR tree must have been configured and built (make modules_prepare at least) with the same configuration as the target kernel.
Integration options
- Yocto: a recipe inheriting
modulebuilds it with the image kernel automatically. - Buildroot:
kernel-modulepackage infrastructure. - DKMS: rebuilds out-of-tree modules automatically when distribution kernels update.
- In-tree: add a Kconfig entry and
obj-$(CONFIG_MYDRV) += mydrv.oto the subsystem's Makefile; upstreaming the driver avoids constant rebuilding for API changes.
Common errors: "Invalid module format" or "disagrees about version of symbol" (built against a different kernel), "Unknown symbol" (missing dependency, or using a GPL-only symbol without a GPL licence), and missing modules_prepare in the build tree.