1.2 多文件内核模块
有些时候在几个源文件之间分出一个内核模块是很有意义的。在这种情况下,你需要
做下面的事情:
1. 在除了一个以外的所有源文件中,增加一行#define __NO_VERSION__。这是很重
要的,因为module.h一般包括kernel_version的定义,这是一个全局变量,包含模
块编译的内核版本。假如你需要version.h,你需要把自己把它包含进去,因为假如
有__NO_VERSION__的话module.h不会自动包含。
2. 象通常一样编译源文件。
3. 把所有目标文件联编成一个。在X86下,用ld –m elf_i386 –r –o .o
<1st source file>
这里给出一个这样的内核模块的例子。
ex start.c
/* start.c
* Copyright (C) 1999 by Ori Pomerantz
*
* "Hello, world" - the kernel module version.
* This file includes just the start routine
*/
/* The necessary header files */
/* Standard in kernel modules */
#include /* We're doing kernel work */
#include /* Specifically, a module */
/* Deal with CONFIG_MODVERSIONS */
#if CONFIG_MODVERSIONS==1
#define MODVERSIONS
#include
#endif
/* Initialize the module */
int init_module()
{
printk("Hello, world - this is the kernel speaking\n");
/* If we return a non zero value, it means that
* init_module failed and the kernel module
* can't be loaded */
return 0;
}
ex stop.c
/* stop.c
* Copyright (C) 1999 by Ori Pomerantz
*
* "Hello, world" - the kernel module version. This
* file includes just the stop routine.
*/
/* The necessary header files */
/* Standard in kernel modules */
#include /* We're doing kernel work */
#define __NO_VERSION__ /* This isn't "the" file
* of the kernel module */
#include /* Specifically, a module */
#include /* Not included by
* module.h because
* of the __NO_VERSION__ */
/* Deal with CONFIG_MODVERSIONS */
#if CONFIG_MODVERSIONS==1
#define MODVERSIONS
#include
#endif
/* Cleanup - undid whatever init_module did */
void cleanup_module()
{
printk("Short is the life of a kernel module\n");
}
ex Makefile
# Makefile for a multifile kernel module
CC=gcc
MODCFLAGS := -Wall -DMODULE -D__KERNEL__ -DLinux
hello.o: start.o stop.o
ld -m elf_i386 -r -o hello.o start.o stop.o
start.o: start.c /usr/include/linux/version.h
$(CC) $(MODCFLAGS) -c start.c
stop.o: stop.c /usr/include/linux/version.h
$(CC) $(MODCFLAGS) -c stop.c