How to create .ko files in Linux
35,842
Solution 1
Create a Makefile
like this.
ifneq ($(KERNELRELEASE),)
obj-m := mymodule.o
else
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
all:
$(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules
install:
$(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules_install
%:
$(MAKE) -C $(KDIR) SUBDIRS=$(PWD) $@
endif
Assuming your module's source is in mymodule.c
, running make
will create mymodule.ko
.
Solution 2
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.
Author by
Anand Sunderraman
Updated on September 17, 2022Comments
-
Anand Sunderraman over 1 year
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?-
Ciro Santilli Путлер Капут 六四事 almost 8 yearsMinimal runnable example to insert on an Ubuntu 16.04 host: github.com/cirosantilli/linux-kernel-module-cheat/tree/…
-
-
Anand Sunderraman over 13 yearsThat 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..
-
Louis Gerbarg over 13 yearsI 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.
-
ephemient over 13 years@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. -
Anand Sunderraman over 13 yearsThen can u explain me the meaning of each sentence in the above make file?