Build a Single in Tree Linux Kernel Module (Debian & Clones)

How misleading and complicated this task should be that I’m writing such an article in 2022?
Anyway, if you struggle compiling a simple, standalone Linux kernel module on Debian, Ubuntu, Mint and the like, here’s the recipe:

  • Fetch linux-source-<version> and linux-headers-<version>
$ sudo apt install linux-source-5.4.0 linux-headers-$(uname -r)

Do not use apt-get source linux-source-<version>, only pain will you find.

  • Untar the fetched archive where you’d like
$ tar jxvf /usr/src/linux-source-5.4.0.tar.bz2
  • Copy your current kernel configuration
$ cd linux-source-5.4.0
$ cp /boot/config-$(uname -r) .config
  • Prepare the build environment
$ make oldconfig scripts prepare modules_prepare
  • Copy current kernel exported symbols file
$ cp /usr/src/linux-headers-$(uname -r)/Module.symvers .
  • Build the module you need
$ make -C . M=arch/x86/kvm
  • Test it
$ sudo insmod arch/x86/kvm/kvm-intel.ko

Eventually backup the current loaded module (modinfo <module>), replace it with your freshly built one and don’t forget to depmod -a.