Thursday, March 26, 2009

How to Compile Your Own Module

Below is a sample module to compile (my_module.c):
#include linux/init.h
#include linux/module.h

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Oguzhan Ozmen");
MODULE_DESCRIPTION("My simple Hello World module");

static int module_init(void){

printk(KERN_ALERT "Hello World\n");

return 0; // success
}

static void __exit module_exit(void){

printk(KERN_ALERT "Goodbye\n");
}

module_init(module_init);
module_exit(module_exit);
Within the directory where my_module.c resides in, create a Makefile whose content is as follows:
obj-m += monitor_blockio.o
Then, generate the kernel object file (.ko) using the following command:
make -C [build_dir] M=$PWD modules
Here, [build_dir] stands for the directory which contains the necessary files to build new kernel modules:
- Makefile
- .config
- module.symVers (module symbol information)
- kernel header files (include/ and include/asm)
In general,
[build_dir] is:
- /lib/modules/$(uname -r)/build OR
- /usr/src/packages/BUILD/kernel-$(uname -r)

(assuming that you are using a distro compiled kernel)