编译模块的Makefile解析

 Makefile

# if not defined KERNELRELEASE, command is running from command line,need invoke kbuild system.

ifeq ($(KERNELRELEASE),)  

  KERNELDIR ?= /linux-2.6.30.4 # the directory of kernel source file  

  PWD := $(shell pwd) # the directory of module source file

modules:  

  $(MAKE) -C $(KERNELDIR) M=$(PWD) modules

modules_install:  

  $(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install

clean:  

  rm -rf *.o *~core.depend.*.cmd *.ko *.mod.c.tmp_versions

.PHONY: modules modules_install clean # if defined KERNELRELEASE, kbuild running

else  

  obj-m:= hello.o # the source file of module endif

#################################################################

该Makefile 在模块构造过程中一般将被调用两次。使用make 时,第一次 KERNELRELEASE 尚未定义。KERNELDIR 将被定义为内核源码路径,PWD 将被赋值为模块源码文件所在路径。然后通过 $(MAKE) -C $(KERNELDIR) M=$(PWD) modules进入内核源码目录调用顶层Makefile 。顶层Makefile 会通过 M=$(PWD) 获得指定的模块源码所在路径,并调用其下的 Makefile。即该Makefile 将被调用第二次,此时将会执行else 后的语句,通过内核顶层Makefile 构建出模块。

原文地址:https://www.cnblogs.com/youngvoice/p/5268198.html