LINUX驱动模块MakeFile详解
2024-04-15
27
0
MakeFile的写法一般如下:
CURRENT_PATH:=$(shell pwd) #模块所在的当前路径
Linux_Kernel:=$(shell uname -r) #linux内核代码的当前版本
Linux_Kernel_PATH:=/home/book/100ask_imx6ull-sdk/Linux-4.9.88 #linux内核路径
all:
make -C $(Linux_Kernel_PATH) M=$(CURRENT_PATH) modules
clean:
make -C $(Linux_Kernel_PATH) M=$(CURRENT_PATH) clean
.PHONY:clean
obj-m+=hello_drv.o
或者如下:
Makefile:
PWD = $(shell pwd)
KERNEL_SRC = /usr/src/linux-source-2.6.15/
obj-m := test.o
module-objs := test.o
all:
$(MAKE) -C $(KERNEL_SRC) M=$(PWD) modules
clean:
rm *.ko
或者:
ifneq ($(KERNELRELEASE),)
obj-m :=hello.o
else
KDIR :=/lib/modules/$(shell uname -r)/build
all:
make -C $(KDIR) M=$(PWD) modules
clean:
rm -f *.ko *.o *.mod.o *.mod.c *.symvers *.order
endif
在当前的Makefile目录下,执行make时,会自动调用当前Makefile文件
由于在Linux源文件目录下的Makefile会定义KERNELRELEASE, 故内容为空。这里的ifneq表示不相等时,明显这里执行时会相等,故执行else后的内容。
定义KDIR变量为/lib/modules/$(shell uname -r)/build
路径
-C 表示执行KDIR目录下的Makefile,然后M返回当前目录,再执行当前目录下的Makefile文件,由于在内核目录下的Makefile定义了KERNELRELEASE,故这里有效,会执行:
obj-m :=hello.o
给表示目录文件 为hello.o(实际为hello.ko,不过这里为固定写法,只能这样写)
然后生成的是由modules,表示生成模块文件
make M=$(PWD) modules
的意思就是生成当前目录下的所有模块,会调用当前目录下的Makefile来生成。
所以执行一次这个Makefile,去进的是2次。
# Use make M=dir to specify directory of external module to build
# 186 # Old syntax make ... SUBDIRS=$PWD is still supported
# 187 # Setting the environment variable KBUILD_EXTMOD take precedence
# External module support.
#1467 # When building external modules the kernel used as basis is considered
#1468 # read-only, and no consistency checks are made and the make
#1469 # system is not used on the basis kernel. If updates are required
#1470 # in the basis kernel ordinary make commands (without M=...) must
#1471 # be used.
#1472 #
#1473 # The following are the only valid targets when building external
#1474 # modules.
#1475 # make M=dir clean Delete all automatically generated files
#1476 # make M=dir modules Make all modules in specified dir
#1477 # make M=dir Same as 'make M=dir modules'
#1478 # make M=dir modules_install
#1479 # Install the modules built in the module directory
#1480 # Assumes install directory is already created
#1481
#1482 # We are always building modules
#@echo ' Building external modules.'
#1530 @echo ' Syntax: make -C path/to/kernel/src M=$$PWD target'
#1531 @echo ''
#1532 @echo ' modules - default target, build the module(s)'
#1533 @echo ' modules_install - install the module'
#1534 @echo ' clean - remove generated files in module directory only'
#1535 @echo ''
附一个简单的hello模块源代码可用于测试
#include <linux/module.h> //所有模块都需要的头文件
#include <linux/init.h> // init&exit相关宏
#include <linux/kernel.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("xxx");
MODULE_DESCRIPTION("hello world module");
static int __init hello_init(void)
{
printk(KERN_WARNING "hello world.\n");
return 0;
}
static void __exit hello_exit(void)
{
printk(KERN_WARNING "hello exit!\n");
}
module_init(hello_init);
module_exit(hello_exit);