error in generating .ko file for simple hello worl

2019-09-06 16:28发布

问题:

I am a beginner in linux kernel development and trying to load a simple module in linux. I have created an hello.c file, to be loaded as kernel module.

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

MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("A Simple Hello World module");

static int __init hello_init(void)
{
    printk(KERN_INFO "Hello world!\n");
    return 0;   
}

static void __exit hello_cleanup(void)
{
    printk(KERN_INFO "Cleaning up module.\n");
}

module_init(hello_init);
module_exit(hello_cleanup);

this hello.c and the makefile both, I have kept in /home/linux/ directory.

makefile

obj-m +=hello.o

src= /usr/src/linux-headers-3.5.0-17-generic
all:
  $(MAKE) -C $(src) SUBDIR-$(PWD) modules
clean:
  rm -rf *.o *.ko

to generate .ko file, when I run the make command on terminal from the /home/linux directory , I get following error

h2o@h2o-Vostro-1015:~/linux$ make
make -C /usr/src/linux-headers-3.5.0-17-generic SUBDIR-/home/h2o/linux modules
make[1]: Entering directory `/usr/src/linux-headers-3.5.0-17-generic'
make[1]: *** No rule to make target `SUBDIR-/home/h2o/linux'.  Stop.
make[1]: Leaving directory `/usr/src/linux-headers-3.5.0-17-generic'
make: *** [all] Error 2

kindly advise what am I missing or doing wrong..

回答1:

  • Makefile

    obj-m := hello.o # Module Name is hello.c

    KDIR := /lib/modules/$(shell uname -r)/build

    all: $(MAKE) -C $(KDIR) M=$(PWD) modules

    clean: $(MAKE) -C $(KDIR) M=$(PWD) clean $(RM) Module.markers modules.order

its not guaranteed that headers file will always be located in /usr/src directory, but it will surely be located in /lib/modules directory.

  • make sure that system has latest header files

to find out which header files to be present run `

uname -r

on terminal, output will be like

3.5.0-17-generic

to install header files run

sudo apt-get install linux-headers-$(uname -r)



回答2:

You have:

$(MAKE) -C $(src) SUBDIR-$(PWD) modules

But it seems like you want:

$(MAKE) -C $(src)/SUBDIR-$(PWD) modules

Or something along those lines; where does the source code live? You need to -C there.



回答3:

Kernel build system is a bit complex. It would be good to read the kernel build process documentation. Which gives better understanding about, say,

  • Targets like --- modules / modules_install
  • Options like --- -C $KDIR / M=$PWD
  • Command Syntax ---
  • $ make -C <path_to_kernel_src> M=$PWD

    $ make -C /lib/modules/uname -r/build M=$PWD

    $ make -C /lib/modules/uname -r/build M=$PWD modules_install

  • Loadable module goals --- obj-m

etc...