关于linux内核模块Makefile的解析

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

 

Linux内核是一种单体内核,可是经过动态加载模块的方式,使它的开发很是灵活 方便。那么,它是如何编译内核的呢?咱们能够经过分析它的Makefile入手。如下是 一个简单的hello内核模块的Makefile. linux

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一下就行。web

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

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

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


首 先,因为make 后面没有目标,因此make会在Makefile中的第一个不是以.开头的目标做为默认的目标执行。因而default成为make的目标。make会执 行  $(MAKE) -C $(KERNELDIR) M=$(PWD) modules  shell是make内部的函数,ui

假设当前内核版本是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的符号连接。spa

可见,make执行了两次。code

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

第二次执行时是执行/usr/src/linux/下的Makefile时. 
可是仍是有很多使人困惑的问题: 1.这个KERNELRELEASE也很使人困惑,它是什么呢?在/home/study/prog/mod/he llo/Makefile中是没有定义这个变量的,因此起做用的是else…endif这一段。

   不过,若是把hello模块移动到内核源代码中。例如放到/usr/src/linux/driver/中, KERNELRELEASE就有定义了。在/usr/src/linux/Makefile中有 162  KERNELRELEASE=$(VERSION).$(PATCHLEVEL).$(SUBLEVEL)$(EXTRAVERSION)$(LOCALVERSION)  这时候,hello模块也再也不是单独用make编译,而是在内核中用make modules进行 编译。用这种方式,该Makefile在单独编译和做为内核一部分编译时都能正常工做。

 
2.这个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:

862 .PHONY: modules

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

864 @echo ' Building modules, stage 2.';

865 $(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会包含不少文件:  011 -include .config 012 013 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。

相关文章
相关标签/搜索