Today's assignment: Makefiles for Kernel Modules

Lets get straight to the point why I created this blog for. I am not your teacher to take you through the basics of Kernel/C programming under linux. ;) and I consider that people reading my blog have a prior knowledge of programming in C. (sorry if this is a jump from beginner's level to Novice...This post is for people who want to stop reading and start coding straightaway. Although I will touch on how things are done in the kernel in several places, that is not my purpose. There are enough good sources which do a better job than I could have done!)


A kernel module is not an independent executable, but an object file which will be linked into the kernel in runtime. As a result, they should be compiled with the -c flag. Also, all kernel modules have to be compiled with certain symbols defined.

  • __KERNEL__ -- This tells the header files that this code will be run in kernel mode, not as part of a user process.
  • MODULE -- This tells the header files to give the appropriate definitions for a kernel module.
  • LINUX -- Technically speaking, this is not necessary. However, if you ever want to write a serious kernel module which will compile on more than one operating system, you'll be happy you did. This will allow you to do conditional compilation on the parts which are OS dependent.

There are other symbols which have to be included, or not, depending on the flags the kernel was compiled with. If you're not sure how the kernel was compiled, look it up in /usr/include/linux/config.h

  • __SMP__ -- Symmetrical MultiProcessing. This has to be defined if the kernel was compiled to support symmetrical multiprocessing (even if it's running just on one CPU). If you use Symmetrical MultiProcessing, there are other things you need to do...lets say Interrupt handling. ;)
  • CONFIG_MODVERSIONS -- If CONFIG_MODVERSIONS was enabled, you need to have it defined when compiling the kernel module and and to include /usr/include/linux/modversions.h. This can also be done by the code itself.

ex Makefile


# Makefile for a basic kernel module

CC=gcc
MODCFLAGS := -Wall -DMODULE -D__KERNEL__ -DLINUX

hello.o: hello.c /usr/include/linux/version.h
$(CC) $(MODCFLAGS) -c hello.c
echo insmod hello.o to turn it on
echo rmmod hello to turn if off
echo
echo X and kernel programming do not mix.
echo Do the insmod and rmmod from outside X.


So, now the only thing left is to su to root , and then insmod
hello and rmmod hello to your heart's content.
While you do it, notice your new kernel module in /proc/modules.


oops...seems much for the day...lol...never mind ...
i will be back with more!
tc all. keep reading. Adios!






Page copy protected against web site content infringement by Copyscape

No comments: