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
");
/* 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
");
}
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