Dhyan Deep A.K
Dhyan Deep A.K

Reputation: 111

Building linux kernel module

Im a windows driver programmer who is a complete newbie in linux kernel development.I have installed linux kernel headers. I am trying my helloworld module in linux kernel.

#include <linux/init.h>
#include <linux/module.h>
/*MODULE_LICENSE("Dual BSD/GPL");*/
static int hello_init(void)
{
    printk(KERN_ALERT "Hello, world\n");
    return 0;
}
static void hello_exit(void)
{
    printk(KERN_ALERT "Goodbye, cruel world\n");
}
module_init(hello_init);
module_exit(hello_exit);

following is the code for my module. makefile for my build is

obj-m +=tryout.o

KDIR =/usr/src/linux-headers-4.13.0-37-generic

all:
    $(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules
clean:
    rm -rf *.o *.ko *.mod.* *.symvers *.order

but im getting 'fatal error: linux/init.h: No such file or directory while making this module'. What could be the possible reason? and how can i resolve it?

Upvotes: 1

Views: 956

Answers (1)

Ahmed Masud
Ahmed Masud

Reputation: 22374

Your Makefile is mis-configured. In particular you used SUBDIRS whereas you're supposed to use M and your $(PWD) is meaningless, you should use pwd to be simple (or $$PWD); Here's how you should set it up:

    ifneq ($(KERNELRELEASE),)
    # kbuild part of makefile
    obj-m  := tryout.o
    # any other c files that you would like to include go into 
    # yourmodule-y := <here> e.g.:

    # tryout-y := tryout-1.o tryout-2.o 

    else
    # normal makefile
    KDIR ?= /usr/src/linux-headers-4.13.0-37-generic

    # you really should set KDIR up as:
    # KDIR := /lib/modules/`uname -r`/build

    all::
        $(MAKE) -C $(KDIR) M=`pwd` $@

    # Any module specific targets go under here
    # 

    endif

Configuring your makefile like this will allow you to simply type make in your module directory and it will invoke the Kernel's kbuild subsystem which will in-turn use the kbuild part of your Makefile.

Read up on https://www.kernel.org/doc/Documentation/kbuild/modules.txt for all the different permutations on how to do this. It comes with examples.

Upvotes: 1

Related Questions