简体   繁体   中英

How to define a function in one linux kernel module and use it in another?

I developed two simple modules to the kernel. Now i want to define a function in one module and after that use it in the other.

How i can do that?

Just define the function and caller in the other module without problems?

Define it in module1.c :

#include <linux/module.h>

int fun(void);
EXPORT_SYMBOL(fun);

int fun(void)
{
    /* ... */
}

And use it in module2.c :

extern int fun(void);

Linux kernel allows modules stacking, which basically means one module can use the symbols defined in other modules. But this is possible only when the symbols are exported. Let us make use of the very basic hello world module. In this module we have added function called "hello_export" and used the EXPORT_SYMBOL macro to export this function.

hello_export.c

#include <linux/init.h>
#include <linux/module.h>
MODULE_LICENSE("Dual BSD/GPL"); 
static int hello_init(void)
{ 
  printk(KERN_INFO "Hello,world");
   return 0; 
}
static hello_export(void) {
 printk(KERN_INFO "Hello from another module");
return 0;
} 
static void hello_exit(void) 
{ 
  printk(KERN_INFO "Goodbye cruel world"); 
} 
EXPORT_SYMBOL(hello_export);

module_init(hello_init); module_exit(hello_exit); Prepare a Makefile ,Compile it using the "make" command and then insert it into the kernel using insmod. $insmod hello_export.ko All the symbols that the kernel is aware of is listed in /proc/kallsyms. Let us search for our symbol in this file.

$ cat /proc/kallsyms | grep hello_export d09c4000 T hello_export[hello_export]

From the output we can see that the symbol we exported is listed in the symbols recognized by the kernel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM