写内核模块Makefile的技巧 收藏
Linux 2.6 的内核使用Kbuild 来编译内核模块。Kbuild 能够编译内核树目录内的内核模块,也能够编译内核树目录外的内核模块(外部内核模块)。
. 编译外部内核模块的命令:
#cd <your-module-dir>
#make -C <path-to-kernel> M=`pwd`
其中<your-module-dir> 为要编译的内核模块所在目录,<path-to-kernel> 为内核源码所在的目录。
对于发行版本的Linux ,可以用:
#make -C /lib/modules/`uname -r`/build M=`pwd`
注意:使用Kbuild 之前,必须先成功编译过内核源码。
说明:
.#make -C <path-to-kernel> M=`pwd` modules
作用与上面的命令一样
. 以前的内核版本可以使用
#make -C <path-to-kernel> SUBDIRS=`pwd` modules
. 安装外部内核模块
#make -C <path-to-kernel> M=`pwd` modules_install
默认安装目录为:/lib/modules/`uname -r`/extra ,可以通过INSTALL_MOD_PATH 宏在默认安装路径前加前缀。
例如:
#make -C <path-to-kernel> INSTALL_MOD_PATH=/opt M=`pwd` modules_install
则编译后的模块会放在 /opt/lib/modules/`uname -r`/extra
通过宏INSTALL_MOD_DIR 可以修改是否放在'extra' 下,例如:
#make -C <path-to-kernel> INSTALL_MOD_DIR=golf M=`pwd` modules_install
则编译后的模块会放在 /lib/modules/`uname -r`/golf
. 编译单个文件
#make -C <path-to-kernel> M=`pwd` <filename>
. 其他命令
#make -C <path-to-kernel> M=`pwd` clean
#make -C <path-to-kernel> M=`pwd` help
.Kbuild 文件
Linux 的Kbuild 会在内核模块目录下查找Kbuild 文件,如果有,则在编译时会使用该文件。
示例:
假设有这么几个文件:8123_if.c 8123_if.h 8123_pci.c 8123_bin.o_shipped( 二进制的模块文件 )
Kbuild 文件的内容:
obj-m := 8123.o
8123-y:8123_if.o 8123_pci.o 8123_bin.o
Makefile 的内容:
# 为了兼容旧版本的 Kbuild
ifneq($(KERNELRELEASE),)
include Kbuild
else
# 正常的 Makefile
KDIR:=/lib/modules/`uname -r`/build
all::
$(MAKE) -C $(KDIR) M=`pwd` $@
# 其他 target
genbin:
echo "X" > 8123_bin_shipped
endif
注意,没有源码的二进制.o 文件必须以原文件名加_shipped 结尾,例如8123_bin.o_shipped ,KBuild 会把 8123_bin.o_shipped
复制为8123_bin.o ,然后一起编译。
.Makefile 中如何包括自己的include 文件
由于采用Kbuild 编译外部内核模块时,编译路径切换到了内核源码树的目录,因此如果在Makefile 中使用相对路径来包含另一个文件
时,会找不到该文件。因此,不能用
include ../config.mk
应该用:
ifeq ($(obj),)
obj= .
endif
include $(obj)/../config.mk
1. 一个实例
cd your_source_dir
make -C /opt/bcm97405/kernel/stblinux-2.6.18 M=`pwd`
insmod *.ko
ifconfig ra0 inet IP_address up
ifconfig ra0 inet IP_address down
lsmod
rmmod *