I'm working on my own netfilter module for the first time. According to internet documentation, The simplest module contains the following C code:

//'Hello World' kernel module, logs call to init_module
// and cleanup_module to /var/log/messages

// In Ubuntu 8.04 we use make and appropriate Makefile to compile kernel module

#define __KERNEL__
#define MODULE

#include <linux/module.h>
#include <linux/kernel.h>

int init_module(void)
 printk(KERN_INFO "init_module() called\n");
 return 0;

void cleanup_module(void)
 printk(KERN_INFO "cleanup_module() called\n");

Then the same page suggests the following contents for a makefile:

obj-m := hello.o
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
    $(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules

When I executed make on the command line, I got a no targets for "default" message.

However, when I changed the makefile to the following:

obj-m := hello.o
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

Executing "make" alone here worked correctly and the C compiler actually ran, and inserting and removing the module worked as expected.

I'm curious. Is the last makefile I showed compatible with every unix operating system (beyond version 2.24)? Currently I'm using Slackware 12 32-bit and I'll be also testing my code on CentOS 6 64-bit and If theres a common makefile that I can create, I'd rather do that, then create a separate makefile for each system.

Can someone give me advice here?


AFAIK, this looks good. The default one I use is a little different. It comes from the Linux Device Drivers book

# To build modules outside of the kernel tree, we run "make"
# in the kernel source tree; the Makefile these then includes this
# Makefile once again.
# This conditional selects whether we are being included from the
# kernel Makefile or not.

    # Assume the source tree is where the running kernel was built
    # You should set KERNELDIR in the environment if it's elsewhere
    KERNELDIR ?= /lib/modules/$(shell uname -r)/build
    # The current directory is passed to sub-makes as argument
    PWD := $(shell pwd)

  $(MAKE) -C $(KERNELDIR) M=$(PWD) modules

  $(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install

  rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions *.order *.symvers

.PHONY: modules modules_install clean

    # called from kernel build system: just declare what our modules are
    obj-m := hello.o
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.