[ 驱动移植 ] [ 2 ] Linux内核编程

模块传参

module_param(name, type, perm);

功能:将指定的全局变量设置成模块参数

用法:首先,在内核模块代码中声明 全局变量 name 作为传参对象。然后,使用该函数告知内核。最后,安装内核时,在模块后为全局变量赋值。

#include <linux/module.h>
#include <linux/kernel.h>

static char* str = "Hello, World!!";

module_param(str, charp, S_IRUSR);

int __init mychar_param_init(void) {
    printk("The string is %s\n", str);
    return 0;
}

void __exit mychar_param_exit(void) {
    printk("exit mychar param\n");
}

MODULE_LICENSE("GPL");
module_init(mychar_param_init);
module_exit(mychar_param_exit);

image.png

注意:在使用 module_param 时,如果操作权限过高会导致编译报错。[ link ]

同理,可以使用 module_param_array 传递数组。

模块依赖

使用导出符号的地方,需要对这些符号进行 extern 声明后才能使用这些符号。

/home/ubuntu/Code/drivers/char/mychar_param.c:4:1: error: multiple storage classes in declaration specifiers
 extern static char* str = "Hello, World!!";
 ^~~~~~
/home/ubuntu/Code/drivers/char/mychar_param.c:4:21: warning: 'str' initialized and declared 'extern'
 extern static char* str = "Hello, World!!";

原因{2}:static 和 extern 都是存储类型,不可以同时使用。

编译时,在引用依赖的地方报出如下错误:

/home/ubuntu/Code/drivers/char/mychar_dep.c:5:45: error: 'str' undeclared (first use in this function)
     printk("The dependence string is %s\n", str);
                                             ^~~

使用函数依赖{3}不会产生如上问题。后来发现,extern 声明应该放在引用外部变量的地方。


参考:

  1. linux驱动: 如何向模块传递参数, module_param和module_param_array
  2. https://stackoverflow.com/questions/34694979/c-declaring-a-variable-with-both-register-and-static-storage-classes
  3. https://www.tianxiaohui.com/index.php/Linux%E7%9B%B8%E5%85%B3/%E5%86%99%E4%B8%80%E4%B8%AA%E6%9C%89%E4%BE%9D%E8%B5%96%E7%9A%84Linux-%E5%86%85%E6%A0%B8%E6%A8%A1%E5%9D%97.html