关于linux内核模块Makefile的解析

转载:http://www.embeddedlinux.org.cn/html/yingjianqudong/201403/23-2820.html

Linux内核是一种单体内核,但是通过动态加载模块的方式,使它的开发非常灵活 方便。那么,它是如何编译内核的呢?我们可以通过分析它的Makefile入手。

  • 以下是 一个简单的hello内核模块的Makefile
ifneq ($(KERNELRELEASE),)
    obj-m := hello.o
else
    KERNELDIR ?= /root/work/latest_codes/linux-stable
    PWD := $(shell pwd)
default:
    $(MAKE) -C $(KERNELDIR) M=$(PWD) modules

clean:
    @rm -rf *.o *.mod.c *.mod.o *.ko *.order *.symvers .*.cmd .tmp_versions
endif

当我们写完一个hello模块,只要使用以上的makefile。然后make一下就行。

假设我们把hello模块的源代码放在/home/study/prog/mod/hello/下。

当我们在这个目录运行make时,make是怎么执行的呢?

LDD3第二章第四节“编译和装载”中只是简略地说到该Makefile被执行了两次,但是具体过程是如何的呢?

首先,由于make后面没有目标,所以make会在Makefile中的第一个不是以.开头的目标作为默认的目标执行。于是default成为make的目标,shell是make内部的函数,所以

make会执行$(MAKE) -C $(KERNELDIR) M=$(PWD) modules

假设当前内核版本是2.6.13-study,所以 $(shell uname -r) 的结果是2.6.13-study 这里,实际运行的是:

 make -C /lib/modules/2.6.13-study/build M=/home/study/prog/mod/hello/ modules

其中/lib/modules/2.6.13-study/build是一个指向内核源代码/usr/src/linux的符号链接。

可见,make执行了两次。

第一次执行时是读hello模块的源代码所在目录/home/study/prog/mod/hello/下的Makefile。

第二次执行时是执行/usr/src/linux/下的Makefile时.

但是还是有不少令人困惑的问题:

  • 这个KERNELRELEASE也很令人困惑,它是什么呢?在/home/study/prog/mod/hello/Makefile中是没有定义这个变量的,所以起作用的是else…endif这一段。

    不过,如果把hello模块移动到内核源代码中。例如放到/usr/src/linux/driver/中, KERNELRELEASE就有定义了。在/usr/src/linux/Makefile中有:

   KERNELRELEASE=$(VERSION).$(PATCHLEVEL).$(SUBLEVEL)$(EXTRAVERSION)$(LOCALVERSION)  

这时候,hello模块也不再是单独用make编译,而是在内核中用make modules进行编译。用这种方式,该Makefile在单独编译和作为内核一部分编译时都能正常工作。

  • 这个obj-m := hello.o什么时候会执行到呢? 在执行:make -C /lib/modules/2.6.13-study/build M=/home/study/prog/mod/hello/ modules时,make
    /usr/src/linux/Makefile中寻找目标modules:
.PHONY: modules

modules: $(vmlinux-dirs) $(if $(KBUILD_BUILTIN),vmlinux)

	@echo ' Building modules, stage 2.';

	$(Q)$(MAKE) -rR -f $(srctree)/scripts/Makefile.modpost

可以看出,分两个stage:

1.编译出hello.o文件。

2.生成hello.mod.o hello.ko

在这过程中,会调用 make -f scripts/Makefile.build obj=/home/study/prog/mod/hello

而在 scripts/Makefile.build会包含很多文件:

-include .config
include $(if $(wildcard $(obj)/Kbuild), $(obj)/Kbuild, $(obj)/Makefile)

其中就有/home/study/prog/mod/hello/Makefile 这时KERNELRELEASE已经存在。

所以执行的是: obj-m:=hello.o

关于make modules的更详细的过程可以在scripts/Makefile.modpost文件的注释 中找到。

如果想查看make的整个执行过程,可以运行make -n

posted @ 2014-04-11 19:43  摩斯电码  阅读(2302)  评论(0编辑  收藏  举报