Compiling a kernel module
Kernel modules need to be compiled with certain gcc options to make them work. In addition, they also need to be compiled with certain symbols defined. This is because the kernel header files need to behave differently, depending on whether we're compiling a kernel module or an executable. You can define symbols using gcc's -D option, or with the #define preprocessor command.
-c: A kernel module is not an independant executable, but an object file which will be linked into the kernel during runtime using insmod. As a result, modules should be compiled with the -c flag.
-O2: The kernel makes extensive use of inline functions, so modules must be compiled with the optimization flag turned on. Without optimization, some of the assembler macros calls will be mistaken by the compiler for function calls. This will cause loading the module to fail, since insmod won't find those functions in the kernel.
-W -Wall: A programming mistake can take take your system down. You should always turn on compiler warnings, and this applies to all your compiling endeavors, not just module compilation.
-isystem /lib/modules/`uname -r`/build/include: You must use the kernel headers of the kernel you're compiling against. Using the default /usr/include/linux won't work.
-D__KERNEL__: Defining this symbol tells the header files that the code will be run in kernel mode, not as a user process.
-DMODULE: This symbol tells the header files to give the appropriate definitions for a kernel module.
We use gcc's -isystem option instead of -I because it tells gcc to surpress some "unused variable" warnings that -W -Wall causes when you include module.h. By using -isystem under gcc-3.0, the kernel header files are treated specially, and the warnings are surpressed.
Sample:
gcc -D__KERNEL__ -DMODULE -I/lib/modules/`uname -r`/build/include -O2 -c testmod.c
This is much simpler in 2.6 kernel refer [2]
for USB drivers if the module needs to be loaded as and when the device is plugged in use
-DCONFIG_HOTPLUG
To solve the problem of unresolved symbols in kernel module
Add the following at the starting to the kernel module source file you are creating.
#if defined __KERNEL__
#include <linux/config.h>
#if defined( CONFIG_MODVERSIONS ) && ! defined( MODVERSIONS )
#define MODVERSIONS
#endif
/* modversions.h should be before should be before module.h */
#if defined( MODVERSIONS )
#include <linux/modversions.h >
#endif
#include "linux/module.h"
#include "linux/version.h"
/* Now your module include files & source code follows */
Related Links:
[1] http://www.tldp.org/LDP/lkmpg/2.4/html/x208.html
[2] http://www.tldp.org/LDP/lkmpg/2.6/html/x181.html
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home