You are on page 1of 17

How to: Compile Linux kernel modules http://www.cyberciti.biz/tips/compiling-linux-kernel-module.

html

About
Forum
Howtos & FAQs
Low graphics
Shell Scripts
RSS/Feed

HKM-Messtechnik GmbH Force measurement Weighing and Sensor technology hkm-messtechnik.de/sensors_scales


Teahan Convoi Service UK Oversize Load Project Management Permits - Pilot Cars - Planning www.teahan-convoi-service.com
AXIe Modular Digitizers 13GHz 40GSPS 64GB FPGA processing, multi channel acquisition modules www.guzik.com

nixcraft - insight into linux admin work

How to: Compile Linux kernel modules


by LinuxTitli on August 22, 2005 · 50 comments

This is one the essential and important task. Many time we upgrade our kernel and some
precompiled drivers won't work with Linux. Especially if you have weird hardware; then
vendor may send you driver code aka C files to compile. Or even you can write your own
Linux kernel driver. Compiling kernel driver is easy. Kernel 2.6.xx makes it even much
more easier. Following steps are required to compile driver as module:

1) You need running kernel source code; if you don't have a source code download it from
kernel.org. Untar kernel source code (tar ball) in /usr/src using tar command:
$ tar -zxvf kernel* -C /usr/src

To be frank kernel headers are more than sufficient to compile kernel modules / drivers. See how to install
kernel headers under Debian / Ubuntu Linux or RHEL / CentOS / Fedora Linux.

2) Next go to your kernel module source code directory and simply create the Makefile file as follows (assuming
your kernel module name is foo):
$ vi Makefile

3) Add following text to it:

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

4) Compile module using make command (module build can be done by any user) :
$ make
It will finally creates the foo.ko module in current directory. You can see all actual compile command stored in
.foo* files in same directory.

5) Once module compiled successfully, load it using insmod or modprobe command. You need to be root user or

1 of 17 2/15/2012 6:16 PM
How to: Compile Linux kernel modules http://www.cyberciti.biz/tips/compiling-linux-kernel-module.html

privileged user to run insmod:


# insmod foo.ko

Example: hello.c module


1) hello.c C source code. Copy following code and save to hello.c
$ mkdir demo; cd demo
$ vi hello.c

2)Add following c source code to it:


#include <linux/module.h> /* Needed by all modules */
#include <linux/kernel.h> /* Needed for KERN_INFO */
#include <linux/init.h> /* Needed for the macros */
static int __init hello_start(void)
{
printk(KERN_INFO "Loading hello module...\n");
printk(KERN_INFO "Hello world\n");
return 0;
}
static void __exit hello_end(void)
{
printk(KERN_INFO "Goodbye Mr.\n");
}
module_init(hello_start);
module_exit(hello_end);

This is an example modified from original source for demonstration purpose.

3) Save the file. Create new Makefile as follows:


$ vi Makefile
Append following make commands:

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

4) Save and close the file.

5) Compile hello.c module:


$ make

6) Become a root user (use su or sudo) and load the module:


$ su -
# insmod hello.ko

Note you can see message on screen if you are logged in as root under run level 3.

7) Verify that module loaded:


# lsmod | less

8) See message in /var/log/message file:

2 of 17 2/15/2012 6:16 PM
How to: Compile Linux kernel modules http://www.cyberciti.biz/tips/compiling-linux-kernel-module.html

# tail -f /var/log/message

9) Unload the module:


# rmmod hello

10) Load module when Linux system comes up. File /etc/modules use to load kernel boot time. This file should
contain the names of kernel modules that are to be loaded at boot time, one per line. First copy your module to
/lib/modules/$(uname -r)/kernel/drivers. Following are suggested steps:

(a) Create directory for hello module:


# mkdir -p /lib/modules/$(uname -r)/kernel/drivers/hello
(b) Copy module:
# cp hello.ko /lib/modules/$(uname -r)/kernel/drivers/hello/
(c) Edit /etc/modules file under Debian Linux:
# vi /etc/modules
(d) Add following line to it:
hello
(e) Reboot to see changes. Use lsmod or dmesg command to verify module loaded or not.
# cat /proc/modules
OR
# lsmod | less

See also:
Read man pages of lsmod, rmmod, modprobe, modules
Documentation located in your kernel source directory (for example /usr/src/linux-2.6.xx.xx
/Documentation/) and README file located under kernel source code tree /usr/src/linux-2.6.xx.xx
/README
Read TLDP.org tutorial online.

Featured Articles:

20 Linux System Monitoring Tools Every SysAdmin Should Know


20 Linux Server Hardening Security Tips
Linux: 20 Iptables Examples For New SysAdmins
My 10 UNIX Command Line Mistakes
25 PHP Security Best Practices For Sys Admins
The Novice Guide To Buying A Linux Laptop
Top 5 Email Client For Linux, Mac OS X, and Windows Users
Top 20 OpenSSH Server Best Security Practices
Top 10 Open Source Web-Based Project Management Software

Share this with other sys admins!


Facebook it - Tweet it - Print it - 1

We're here to help you make the most of sysadmin work. So, subscribe!

{ 50 comments… read them below or add one }

3 of 17 2/15/2012 6:16 PM
How to: Compile Linux kernel modules http://www.cyberciti.biz/tips/compiling-linux-kernel-module.html

1 Anonymous August 23, 2005

Aha … intresting gone try this.

Reply

2 swift May 4, 2007

hi when i compile this by running make file this type of erro occcur …what to do

make -f make
make -C /lib/modules/2.6.18-1.2798.fc6/build M=/home/mclamna modules
make[1]: Entering directory `/usr/src/kernels/2.6.18-1.2798.fc6-i686′
scripts/Makefile.build:17: /home/mclamna/Makefile: No such file or directory
make[2]: *** No rule to make target `/home/mclamna/Makefile’. Stop.
make[1]: *** [_module_/home/mclamna] Error 2
make[1]: Leaving directory `/usr/src/kernels/2.6.18-1.2798.fc6-i686′
make: *** [all] Error 2

Reply

3 shan January 18, 2008

dis s wat i encountered wen using

CHK include/linux/version.h
CHK include/linux/utsrelease.h
HOSTCC scripts/basic/fixdep
In file included from /usr/include/bits/posix1_lim.h:153,
from /usr/include/limits.h:145,
from /usr/lib/gcc/i486-linux-gnu/4.1.2/include/limits.h:122,
from /usr/lib/gcc/i486-linux-gnu/4.1.2/include/syslimits.h:7,
from /usr/lib/gcc/i486-linux-gnu/4.1.2/include/limits.h:11,
from scripts/basic/fixdep.c:113:
/usr/include/bits/local_lim.h:36:26: error: linux/limits.h: No such file or directory
In file included from /usr/include/sys/socket.h:35,
from /usr/include/netinet/in.h:24,
from /usr/include/arpa/inet.h:23,
from scripts/basic/fixdep.c:115:
/usr/include/bits/socket.h:310:24: error: asm/socket.h: No such file or directory
scripts/basic/fixdep.c: In function ‘use_config’:
scripts/basic/fixdep.c:204: error: ‘PATH_MAX’ undeclared (first use in this function)
scripts/basic/fixdep.c:204: error: (Each undeclared identifier is reported only once
scripts/basic/fixdep.c:204: error: for each function it appears in.)
scripts/basic/fixdep.c:204: warning: unused variable ‘s’
scripts/basic/fixdep.c: In function ‘parse_dep_file’:
scripts/basic/fixdep.c:300: error: ‘PATH_MAX’ undeclared (first use in this function)
scripts/basic/fixdep.c:300: warning: unused variable ‘s’
make[1]: *** [scripts/basic/fixdep] Error 1
make: *** [scripts_basic] Error 2

4 of 17 2/15/2012 6:16 PM
How to: Compile Linux kernel modules http://www.cyberciti.biz/tips/compiling-linux-kernel-module.html

Reply

4 Nitin May 24, 2008

Hi swift, I guess u have not created Makefile in ur present directory, plz make sure that makefile name is
correct and its case sensitive, it should be ‘Makefile’.

Reply

5 Nitin June 3, 2008

Hi, This was very much helpful but now I’m stuck because i didn’t understand how this particular
makefile is working, so i’m not able to write it for multiple files. Please could anyone explain how this
makefile works with a example for multiple files.
Thanks,
Nitin.

Reply

6 john June 6, 2008

how to cross compile lkm for arm?

Reply

7 Mohammad August 11, 2008

Dear Vivek ,
Thanks alots for yr teaching.
i compile a new module on fedora core 6 and make it very good. but in fedora i dont know how to submit
for when linux start up , can load automaticly. i didnot find /etc/modules in fedora.

Reply

8 touristguy87 November 4, 2008

I followed the instructions as written even copying and pasting the code, I got nada.

I was able to install the headers using


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

then I copied and pasted the hello.c text and the Makefile from this page but I got nothing.
make: Nothing to be done for ‘all’.

I must be missing something

this is in Ubuntu 8.04

Reply

9 touristguy87 November 8, 2008

ok I got it somehow, honestly I am not sure how but I patched my install (now running kernel-headers

5 of 17 2/15/2012 6:16 PM
How to: Compile Linux kernel modules http://www.cyberciti.biz/tips/compiling-linux-kernel-module.html

2.6.24-21 generic) and rebooted, sudo -i, just tried running make and it worked.

before I was getting “can’t find target ‘make’ error that seems so common. It now is working!!!

Reply

10 mangesh November 20, 2008

how do I cross compile a module using kbuild. Please help

Reply

11 mix January 7, 2009

The reason that make: Nothing to be done for ‘all’ is you should modify the Makefile, replace the space in
each make command with tab.

Reply

12 s singh February 7, 2011

i am getting the same error and replacing spaces with tab is not working.
some other solution..??

Reply

13 kernelmodule January 22, 2009

After executing the insmod the message is not being displayed…Can u pls guide me on whats goin
wrong?

Reply

14 Anjan January 13, 2011

try looking for messages in dmesg i.e., after #insmod hello.ko


try #dmesg
u will be able to see the messages

Reply

15 scrat January 23, 2009

Oh, big thanks, source of Makefile is very helpful.

Reply

16 Victor May 18, 2009

Hi,

I’m trying to compile your hello.c module in a Fedora Core 9 with a 2.6.27.21-78.2.41.fc9.i686 kernel.
My gcc compiler is 4.3.0 20080428 (Red Hat 4.3.0-8) (GCC). My kernel-devel package is installed with

6 of 17 2/15/2012 6:16 PM
How to: Compile Linux kernel modules http://www.cyberciti.biz/tips/compiling-linux-kernel-module.html

my current kernel version.

When I try to compile I get the following:

root@leela:[~/pruebas-modulos]$ make
make -C /lib/modules/2.6.27.21-78.2.41.fc9.i686/build M=/root/pruebas-modulos modules
make[1]: se ingresa al directorio `/usr/src/kernels/2.6.27.21-78.2.41.fc9.i686′
Building modules, stage 2.
MODPOST 0 modules
make[1]: se sale del directorio `/usr/src/kernels/2.6.27.21-78.2.41.fc9.i686′

root@leela:[~/pruebas-modulos]$ ls
hello.c hello.o Makefile Module.markers modules.order Module.symvers
root@leela:[~/pruebas-modulos]$

As you can see I do not obtain the .ko file. I have searched across the web in order to understand why I am
not getting my .ko file, but I am not able to find anything useful. I would appreciate if you could help me
to find why the makefile is not working

Thanks in advance,
Víctor.

Reply

17 tonychen123@qq.com June 5, 2009

Hey, check that you makefile if you make a mistake with “obj-m” with “obj_m”, I have the same problem
as you do.
When I write “obj-m” instead of “obj_m”, everything goes good.

Reply

18 reveil July 27, 2009

Be sure you have tabs instead of spaces in the Makefile. Obvious and common mistake but took me a few
minutes to figure this out after copy-pasting.

Reply

19 shreyas karmahe August 24, 2009

hi,
could u please tell me how can i install the kernel updates as I despirately need linux source code.

Reply

20 blaine September 23, 2009

Thank you for posting this. It is very hard to figure out how to just make a single module manually. This
post should be ranked higher when searching “How to compile a single kernel module”. Self fulfilling
prophecy, perhaps?

7 of 17 2/15/2012 6:16 PM
How to: Compile Linux kernel modules http://www.cyberciti.biz/tips/compiling-linux-kernel-module.html

Reply

21 Adam October 14, 2009

Thanks, this ended a few hours of frustration.

Reply

22 Alok November 4, 2009

Hi
I have tried load module when Linux system comes up but it’s not displaying in
#cat /proc/modules
I have done these things successfully.
# mkdir -p /lib/modules/$(uname -r)/kernel/drivers/hello
# cp hello.ko /lib/modules/$(uname -r)/kernel/drivers/hello/
# vi /etc/modules

and Added “hello” word in next line.


any suggestion would be welcome

with regards
Alok

Reply

23 abhi January 10, 2010

Thanks a lot. Found this article v. useful

Reply

24 Arnab Chakraborty January 17, 2010

Hi,

I found the article very helpful. Unlike many other linux tutorials, this one worked (with me) within the
first few attempts! Just one minor point:

I had to change
tail -f /var/log/message
to
tail -f /var/log/messages

Arnab.

Reply

25 mario March 23, 2010

Be sure , tabs instead of spaces in the Makefile!!!!!!!!

Reply

8 of 17 2/15/2012 6:16 PM
How to: Compile Linux kernel modules http://www.cyberciti.biz/tips/compiling-linux-kernel-module.html

26 Alvaro March 25, 2010

Please can anybody help me out, I need to add the pktgen module, but I’m finding it difficult
Thanks in advance

Reply

27 Martin April 3, 2010

hi
thanks for that article. I try to compile a helloworld.c against the sources of my running kernel now quite a
while without success. First the distro-kernel, and then also the kernel.org kernel. It all looks good to me.
make enters the right directories. the error is _always_ “No Rule for target ….. ” like in the first comment
above.

I don’t really understand all about the makefile. make is called from inside the kernel tree through the
makefile right? Still, it really should be fine, but it doesnt work. Does anybody have a hint?

Reply

28 Zed April 4, 2010

Hi guys… I’m getting really desperate, I need to program a network device drivers for one of my projects,
and I can’t even get the hello world done properly !

I followed the protocol above, and when it comes to the make command, here is what I get:

root@ubuntu:/usr/src/linux-source-2.6.31/include# make

make -C /lib/modules/2.6.31-20-generic/build M=/usr/src/linux-source-2.6.31/include modules


make[1]: Entering directory `/usr/src/linux-headers-2.6.31-20-generic’
Building modules, stage 2.
MODPOST 0 modules
make[1]: Leaving directory `/usr/src/linux-headers-2.6.31-20-generic’

So no hello.ko file generated ! I already spent so many hours on this, checked that I have tabs instead of
spaces in the makefile, and nothing changed…

Thanks for your help guys !

zed

Reply

29 Vlad June 21, 2010

I found an error in Makefile you have:

$(PWD) should be $(shell pwd)

Since PWD is not defined, I think it attempts to compile the entire kernel source.
It solved this error I got:
“make[2]: *** No rule to make target `kernel/bounds.c’, needed by `kernel/bounds.s’. Stop.”

9 of 17 2/15/2012 6:16 PM
How to: Compile Linux kernel modules http://www.cyberciti.biz/tips/compiling-linux-kernel-module.html

Reply

30 smash July 21, 2010

Thanks a lot to mix and reveil for pointing out the tabs in place of spaces. I spent like 3 hrs trying to build
a module from another site, and had no clue what was wrong. It all boiled down to tabs.
Also thanks to whoever made this tut. :)

Reply

31 touristguy87 July 21, 2010

One thing I learned from this exercise is to always start from a working example.

Reply

32 Tapas Mishrae August 21, 2010

Checked it.
Following is my program
#include
#include
#include
extern void *sys_table[];
asmlinkage int(*main_sys_exit)(int);
asmlinkage int alt_exit_function(int err_code)
{
printk(“Sys_exit called with err_code=%d\n”,err_code);
return main_sys_exit(err_code);
}

int init_module()
{
main_sys_exit=sys_table[__NR_exit];
sys_table[__NR_exit]=alt_exit_function;
}
void cleanup_module()
{
sys_table[__NR_exit]=main_sys_exit;
}

and following is make file


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

but I got error

make -C /lib/modules//build/M=/home/tapas/LKP/pandora/temp/sample2 modules

10 of 17 2/15/2012 6:16 PM
How to: Compile Linux kernel modules http://www.cyberciti.biz/tips/compiling-linux-kernel-module.html

make: *** /lib/modules//build/M=/home/tapas/LKP/pandora/temp/sample2: No such file or directory.


Stop.
make: *** [all] Error 2

where as I had installed Kernel headers.

Reply

33 touristguy87 August 21, 2010

START WITH THE EXAMPLE, WHICH HAS BEEN DEBUGGED & TESTED FOR YOU.
If you cannot get that to work that is one thing.
If you can get THAT to work but you cannot get YOUR code to work then
for chrissakes
figure out what you have done different that doesn’t work and fix it l!!!!

Reply

34 Lucas November 18, 2010

hello,
my system is ubuntu 10.04 kernel 2.6.32-25-generic, i did everything as described in article and.. when i
do(as root: sudo -i ):
# insmod hello.ko
i get answer :
# insmod: error inserting ‘hello.ko’: -1 Invalid module format

And I’ve no idea what can be wrong.. or what I do wrong… would be gratefull for help

Reply

35 PAgore November 19, 2010

Cool! :-)
I compiled my first module in Linux.

Thanks for your instructions!!!

Reply

36 Prashant November 21, 2010

I made a hello-1.c and Makefile in the same directory.


when is issue “make” command, it gives error:
make −C /lib/modules/2.6.32-25-generic/build M=/home/prashant modules
make[1]: Entering directory `/home/prashant’
make[1]: *** No rule to make target `−C’. Stop.
make[1]: Leaving directory `/home/prashant’
make: *** [all] Error 2

I am getting this error from so long. I even changed my working directory to root.

11 of 17 2/15/2012 6:16 PM
How to: Compile Linux kernel modules http://www.cyberciti.biz/tips/compiling-linux-kernel-module.html

Reply

37 Suneel October 29, 2011

How did you fix this problem Prashanth? I’m getting exactly same error make[1]: *** No rule to
make target `−C’. Stop. Please help me if you have some info on this.

Reply

38 SIFE December 1, 2010

I have trouble with my custom kernel for the last tow days, it does not boot due [b]ahci[/b] module, can I
compile it as module and then make initrd image or I have to add it to kernel configuration, if so where I
have to activate it, I tried to go to:
Device drivers-> Serial ATA Drivers and Parelle ATA Drivers-> AHCI SATA Support
But it seems does not compile it according to this message when I install modules:
[code]
WARNING: No module ahci found for kernel 2.6.37-rc4, continuing anyway
[/code]

Reply

39 SIFE December 1, 2010

I have trouble with my custom kernel for the last tow days, it does not boot due ahci module, can I
compile it as module and then make initrd image or I have to add it to kernel configuration, if so where I
have to activate it, I tried to go to:
Device drivers-> Serial ATA Drivers and Parelle ATA Drivers-> AHCI SATA Support
But it seems does not compile it according to this message when I install modules:

WARNING: No module ahci found for kernel 2.6.37-rc4, continuing anyway

Reply

40 Prabhu December 8, 2010

Cool article. My first module programming is running successfully. Thanks a lot.


- Prabhu

Reply

41 Romy January 28, 2011

Really Thankful…..A great note for Beginners

Reply

42 Rigved Rakshit February 4, 2011

The line:

obj-m = foo.o

12 of 17 2/15/2012 6:16 PM
How to: Compile Linux kernel modules http://www.cyberciti.biz/tips/compiling-linux-kernel-module.html

is wrong. It should be:

obj-m += foo.o

Reply

43 s singh February 7, 2011

i am getting the following error after executing make


make: Nothing to be done for `all’.

Reply

44 alexpally April 10, 2011

You must use TABs instead of spaces in make file

Reply

45 touristguy87 February 14, 2011

um, obviously one part of the problem here is the fact that depending on what editor you use, what exactly
the offsets are between different sections of the relevant files and whether you use spaces or tabs, you will
get different results.

that’s on top of exactly what version of Linux you’re running, and what version of the relevant libraries.

Trust me on this. Start with a working example, one that you simply download and run, with no edits. If
you don’t have one find one on the internet somewhere. The most that you can pick up from a guide like
this are just guidelines for what should work. Doesn’t mean that it will work for you on your system, the
way that you’ve configured it or edited the file.
When it should work and it does not? odds are that you are about to learn something new about Linux.
good luck

Reply

46 touristguy87 February 14, 2011

also remember that there is a difference between ‘ and `


just as between space and tab
so if you see one don’t use the other

Reply

47 touristguy87 March 1, 2011

If you’re really having trouble getting this to fly, then I would suggest reading this:
http://www.gnu.org/software/make/manual/make.html#Overview
The full documentation on gnu make
probably will help a lot.
and as always
start with something that works and make minimal changes between verifications

13 of 17 2/15/2012 6:16 PM
How to: Compile Linux kernel modules http://www.cyberciti.biz/tips/compiling-linux-kernel-module.html

something as small as a simple tab where the make utility expects spaces or vice-versa
will definitely keep it from working. Not to mention an out-of-date install or an install that needs a reboot.

Reply

48 Iranist September 22, 2011

It was so useful, thanks!

Reply

49 Debian user November 11, 2011

Debian Squeeze 2.6.32-5-amd64

It worked right away!

Thank you. ^^

– screen dump –
Module Size Used by
hello 786 0
powernow_k8 10978 1
cpufreq_stats 2740 0
cpufreq_conservative 5162 0
cpufreq_userspace 1992 0
parport_pc 18855 0
cpufreq_powersave 902 0
ppdev 5030 0

Reply

50 Kesava November 14, 2011

Hi,
when I try to do the same with the different code; getting the following error. Any Help is really
appreciated.

> make
make -C /lib/modules/2.6.25.5-1.1-default/build SUBDIRS=/home/vmware1/netp15 modules
make[1]: Entering directory `/usr/src/linux-2.6.25.5-1.1-obj/x86_64/default’
make[1]: *** No rule to make target `modules’. Stop.
make[1]: Leaving directory `/usr/src/linux-2.6.25.5-1.1-obj/x86_64/default’
make: *** [all] Error 2

-Thnx,
VKS.

Reply

Leave a Comment

14 of 17 2/15/2012 6:16 PM
How to: Compile Linux kernel modules http://www.cyberciti.biz/tips/compiling-linux-kernel-module.html

Name *

E-mail *

Website

You can use these HTML tags and attributes for your code and commands: <strong> <em> <ol> <li> <u> <ul>
<blockquote> <pre> <a href="" title="">

Notify me of followup comments via e-mail.

Security Question:
What is 15 + 6 ?

Are you a human being? Solve the simple math so we know that you are a human and not a bot.

Tagged as: kernel module, kernel source code, linux kernel driver, make command, makefile, module source code, tar command, vi
command

Previous post: Linux MySQL server monitoring

Next post: Howto Reboot or halt Linux system in emergency

GET FREE TIPS & NEWS


Make the most of Linux Sysadmin work!

42k+ Subscribers | Twitter | Google +

15 of 17 2/15/2012 6:16 PM
How to: Compile Linux kernel modules http://www.cyberciti.biz/tips/compiling-linux-kernel-module.html

Find us on Facebook

nixCraft
Like

18,857 people like nixCraft.

Sudha Abdelouahab Inderjeet ស័យយា៉ នត

Teec Haris Jitendra Rakesh Ohm

Facebook social plugin

16 of 17 2/15/2012 6:16 PM
How to: Compile Linux kernel modules http://www.cyberciti.biz/tips/compiling-linux-kernel-module.html

Related Posts

Programming Tutorial: How To Write a FreeBSD Kernel Module ( Driver )


Howto: Build Linux Kernel Module Against Installed Kernel w/o Full Kernel Source Tree
How to: Compile Linux kernel 2.6

©2004-2012 nixCraft. All rights reserved. Cannot be reproduced without written permission.
Privacy Policy | Terms of Service | Questions or Comments | Copyright Info | Sitemap

17 of 17 2/15/2012 6:16 PM

You might also like