关于linux内核模块Makefile的解析
2015-12-23 16:52
561 查看
ifneq ($(KERNELRELEASE),)
obj-m:=hello.o
else
KERNELDIR:=/lib/modules/$(shell uname -r)/build
PWD:=$(shell pwd)
default:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
clean:
rm -rf *.o *.mod.c *.mod.o *.ko
endif
当我们写完一个hello模块,只要使用以上的makefile。然后make一下就行。
假设我们把hello模块的源代码放在/home/study/prog/mod/hello/下。
当我们在这个目录运行make时,make是怎么执行的呢?
LDD3第二章第四节“编译和装载”中只是简略地说到该Makefile被执行了两次,但是具体过程是如何的呢?
首先,由于make 后面没有目标,所以make会在Makefile中的第一个不是以.开头的目标作为默认的目标执行。于是default成为make的目标。make会执行 $(MAKE) -C $(KERNELDIR) M=$(PWD) modules shell是make内部的函数,
假设当前内核版本是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/s tudy/prog/mod/hello/下的Makefile。
第二次执行时是执行/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。
相关文章推荐
- linux编程进阶书推荐APUE,UNP
- Linux strace命令
- (原)Linux下 安装jdk8
- centos6.4安装及升级gcc 4.8.2(已实践)
- linux中查看硬件温度的命令
- linux命令(1):touch
- Linux超快速安装Ruby on Rails
- Linux/Unix下安装MySQLdb的简单方式
- Linux 常用正则表达式
- windows下linux内核源代码阅读 Source Insight3.5工具
- linux命令之awk终极系列
- 对于linux下system()函数的深度理解(整理)
- Android刷linux系统
- Linux编程基础——GDB(设置断点)
- Linux的查找命令
- linux 常用命令
- CentOS6.5-升级GCC5.3.0
- Linux下时间戳格式和标准时间格式的转换
- ubuntu linux 下wine的使用
- linux64需要增加的依赖库