Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have written one driver for one device in Linux. How can I create (using gcc) a .ko file so that I can insert it into the kernel?

share|improve this question
up vote 7 down vote accepted

Create a Makefile like this.

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

Assuming your module's source is in mymodule.c, running make will create mymodule.ko.

share|improve this answer
That fine...But i want to know which option is specifically given to build it as *.ko like -c for *.o , or -fpic -shared for *.so for gcc.. – Renjith G Dec 8 '10 at 7:01
I don't think gcc have such option. Either .ko is just another name for *.a/.so or (what is more probable) it is postprocessed by some script. – Maciej Piechotka Dec 8 '10 at 22:17
@Renjith G: Exactly how a .ko is made may change from kernel release to kernel release, and the only way to make sure you work with the kernel is to use the kernel's Makefiles. – ephemient Dec 8 '10 at 22:54
Then can u explain me the meaning of each sentence in the above make file? – Renjith G Dec 9 '10 at 3:56

Short answer: you can't. A .ko file is more than just a compiled version of your driver source. The kernel build system includes some extra information for instance (compiler version, module dependencies, ...).

You can probably dig through the kernel build system to find all required operations, but you shouldn't. It will almost certainly break with the next kernel release, or the one after that. You should use the makefile ephemient supplied.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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