Template Information

Trang

Compiling Modules

Thứ Bảy, 4 tháng 6, 2011 / 20:30

Once you have everything set up, creating a makefile for your module is straightforward.
In fact, for the “hello world” example shown earlier in this chapter, a single
line will suffice:
obj-m := hello.o
Readers who are familiar with make, but not with the 2.6 kernel build system, are
likely to be wondering how this makefile works. The above line is not how a traditional
makefile looks, after all. The answer, of course, is that the kernel build system
handles the rest. The assignment above (which takes advantage of the extended syntax
provided by GNU make)states that there is one module to be built from the
object file hello.o. The resulting module is named hello.ko after being built from the
object file.
If, instead, you have a module called module.ko that is generated from two source
files (called, say, file1.c and file2.c), the correct incantation would be:
obj-m := module.o
module-objs := file1.o file2.o
For a makefile like those shown above to work, it must be invoked within the context
of the larger kernel build system. If your kernel source tree is located in, say,your ~/kernel-2.6 directory, the make command required to build your module
(typed in the directory containing the module source and makefile) would be:
make -C ~/kernel-2.6 M=`pwd` modules
This command starts by changing its directory to the one provided with the -C
option (that is, your kernel source directory). There it finds the kernel’s top-level
makefile. The M= option causes that makefile to move back into your module source
directory before trying to build the modules target. This target, in turn, refers to the list
of modules found in the obj-m variable, which we’ve set to module.o in our examples.
Typing the previous make command can get tiresome after a while, so the kernel
developers have developed a sort of makefile idiom, which makes life easier for those
building modules outside of the kernel tree. The trick is to write your makefile as follows:
# If KERNELRELEASE is defined, we've been invoked from the
# kernel build system and can use its language.
ifneq ($(KERNELRELEASE),)
obj-m := hello.o
# Otherwise we were called directly from the command
# line; invoke the kernel build system.
else
KERNELDIR ?= /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
default:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
endif

0 nhận xét:

Đăng nhận xét