Complete Communications Engineering

A Linux kernel module contains code that can be added or removed from the kernel at runtime using command line utilities (insmod, rmmod).  Linux development using kernel modules can be more convenient than developing built-in code because the kernel modules are usually smaller than the entire kernel image, and they can usually be tested without re-booting the target system.

Setting up Linux to build a new kernel module requires creating and modifying a few files in the kernel source code.  Usually, the new module will have its own folder under an existing folder.  The best parent folder depends on what the new modules does and what existing kernel features it builds on.  The new folder must contain a menu config file (Kconfig) and a make file (Makefile).  The following is a minimal example:

Kconfig

menuconfig CUSTOM_MODULE

    tristate “Support for a Custom Linux Module”

Makefile

custom-module-objs = source_code.o

obj-$(CONFIG_CUSTOM_MODULE) += custom-module.o

The menu config file defines a new menu option that can be set to either off, on or M.  If it’s on, it will be built into the main kernel image.  If it’s M it will be built as a kernel module.  The make file defines a kernel module called ‘custom-module.ko’.  It contains one source file, ‘source_code.c’.

After the folder and files are in place, the Linux kernel needs a way to find them.  This is done by modifying the corresponding menu config file and make file in the parent folder.  New lines must be added that refer to the new files, as in the following example:

Kconfig

source “cmod/Kconfig”

Makefile

obj-$(CONFIG_MOD) += cmod/

In these examples, ‘cmod’ is the folder containing the new module and CONFIG_MOD is an existing kernel option that the new custom module depends on.  Once all of these changes are in place, the kernel can be configured and built with the new module.  To configure, run ‘make menuconfig’, find the new option and enable it (select ‘M’ to generate a kernel module).  To build, run ‘make’.  The Linux build system should build the new kernel module and generate a ‘.ko’ file for it.  That file can be loaded into the kernel on the target system for testing.