linux指令 make -C ..... M =....
我们可以为代码清单4.1的模板编写一个简单的Makefile:
obj-m := hello.o
并使用如下命令编译Hello World模块:
make -C /usr/src/linux-2.6.15.5/ M=/driver_study/ modules
如果当前处于模块所在的目录,则以下命令与上述命令同等:
make –C /usr/src/linux-2.6.15.5 M=$(pwd) modules
其中-C后指定的是Linux内核源代码的目录,而M=后指定的是hello.c和Makefile所在的目录,编译结果如下:
[root@localhost driver_study]# make -C /usr/src/linux-2.6.15.5/ M=/driver_study/ modules
make: Entering directory `/usr/src/linux-2.6.15.5'
CC [M]/driver_study/hello.o
/driver_study/hello.c:18:35: warning: no newline at end of file
Building modules, stage 2.
MODPOST
CC /driver_study/hello.mod.o
LD [M]/driver_study/hello.ko
make: Leaving directory `/usr/src/linux-2.6.15.5'
从中可以看出,编译过程中,经历了这样的步骤:先进入Linux内核所在的目录,并编译出hello.o文件,运行MODPOST会生成临时的hello.mod.c文件,而后根据此文件编译出hello.mod.o,之后连接hello.o和hello.mod.o文件得到模块目标文件hello.ko,最后离开Linux内核所在的目录。
中间生成的hello.mod.c文件的源代码如代码清单4.7所示。
代码清单4.7 模块编译时生成的.mod.c文件
1 #include <linux/module.h>
2 #include <linux/vermagic.h>
3 #include <linux/compiler.h>
4
5 MODULE_INFO(vermagic, VERMAGIC_STRING);
6
7 struct module __this_module
8 __attribute__((section(".gnu.linkonce.this_module"))) = {
9 .name = KBUILD_MODNAME,
10 .init = init_module,
11 #ifdef CONFIG_MODULE_UNLOAD
12 .exit = cleanup_module,
13 #endif
14 };
16 static const char __module_depends[]
17 __attribute_used__
18 __attribute__((section(".modinfo"))) =
19 "depends=";
hello.mod.o产生了ELF(Linux所采用的可执行/可连接的文件格式)的2个节,即modinfo和.gun.linkonce.this_module。
如果一个模块包括多个.c文件(如file1.c、file2.c),则应该以如下方式编写Makefile:
obj-m := modulename.o
modulename-objs := file1.o file2.o
-----------------------------------------------------------------
4.9模块的编译
----------------------------------------------------------------------
2.4内核中,模块的编译只需内核源码头文件;需要在包含linux/modules.h之前定义MODULE;编译、连接后生成的内核模块后缀为.o。
2.6内核中,模块的编译需要配置过的内核源码;编译、连接后生成的内核模块后缀为.ko;编译过程首先会到内核源码目录下,读取顶层的Makefile文件,然后再返回模块源码所在目录。