next up previous contents index
Next: Character Device Files Up: Hello, world Previous: Makefiles for Kernel Modules

     
Multiple File Kernel Modules

Sometimes it makes sense to divide a kernel module between several source files. In this case, you need to do the following:

1.
In all the source files but one, add the line #define __NO_VERSION__. This is important because module.h normally includes the definition of kernel_version, a global variable with the kernel version the module is compiled for. If you need version.h, you need to include it yourself, because module.h won't do it for you with __NO_VERSION__.        

2.
Compile all the source files as usual.

3.
Combine all the object files into a single one. Under x86, do it with ld -m elf_i386 -r -o <name of module>.o <1st source file>.o <2nd source file>.o.   

Here's an example of such a kernel module.

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 <linux/kernel.h>   /* We're doing kernel work */
#include <linux/module.h>   /* Specifically, a module */



/* Deal with CONFIG_MODVERSIONS */
#if CONFIG_MODVERSIONS==1
#define MODVERSIONS
#include <linux/modversions.h>
#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 <linux/kernel.h>   /* We're doing kernel work */

#define __NO_VERSION__      /* This isn't "the" file 
                             * of the kernel module */
#include <linux/module.h>   /* Specifically, a module */

#include <linux/version.h>   /* Not included by 
                              * module.h because 
                              * of the __NO_VERSION__ */



/* Deal with CONFIG_MODVERSIONS */
#if CONFIG_MODVERSIONS==1
#define MODVERSIONS
#include <linux/modversions.h>
#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


next up previous contents index
Next: Character Device Files Up: Hello, world Previous: Makefiles for Kernel Modules

1999-05-19