4

What is the need of using MACROs like module_init and module_exit while writing Loadable Kernel Modules? Also, Why are we using MACROs like __init or __exit. Even though we can do the job without using them.

  1. Without MACROS

     /*
     Without using MACROS
     Date: 14 Dec 2014
     */
     #include <linux/module.h>
     #include <linux/kernel.h>
     int init_module(void){
         printk(KERN_ALERT "This is our first program.");
         return 0;
     }
     void cleanup_module(void){
         printk(KERN_ALERT "End of our first program.");
     }
    
  2. With MACROs

     /* 
     Edited first.c; Added macros module_init and module_exit
     Date: 14 Dec 2014
     */
     #include <linux/module.h>
     #include <linux/kernel.h>
     #include <linux/init.h>
    
     static int __init first_init(void)
     {
         printk(KERN_ALERT "This is our first program.");
         return 0;
     }
    
     static void __exit first_exit(void)
     {
         printk(KERN_ALERT "End of our first program.");
     }
    
     module_init(first_init);
     module_exit(first_exit);
    

What is the difference?

bittterbotter
  • 445
  • 6
  • 18
  • 1
    possible duplicate of [module\_init and init\_module of linux](http://stackoverflow.com/questions/3218320/module-init-and-init-module-of-linux) – askb Dec 14 '14 at 13:32

1 Answers1

6

module_{init,exit}() adds the necessary boilerplate to initialize / cleanup the module and run the entry / exit code, when the module file is loaded / unloaded into or from the kernel space.

__init is telling kernel that this function is executed once and never come back mainly for built-in drivers while module_init() is to initialize the module when it is being insmod.

Refer Rubini & Corbet

"

The attribute __init, , will cause the initialization function to be discarded, and its memory reclaimed, after initialization is complete. It only works, however, for built-in drivers; it has no effect on modules. __exit, instead, causes the omission of the marked function when the driver is not built as a module; again, in modules, it has no effect.

The use of __init (and __initdata for data items) can reduce the amount of memory used by the kernel. There is no harm in marking module initialization functions with __init, even though currently there is no benefit either. Management of initialization sections has not been implemented yet for modules, but it's a possible enhancement for the future.

"

askb
  • 6,501
  • 30
  • 43