varch/doc/init.md
2024-07-21 19:02:13 +08:00

66 lines
2.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 介绍
初始化导出模块在程序开发中扮演关键角色,它们实现代码的重用和组织的模块化。通过初始化和导出模块,开发者能够将不同功能划分至独立文件中,减少代码冗余,提高维护性和可读性。以下探讨初始化导出模块的作用及其在不同编程语言中的实现方法。
模块的基本作用
封装性: 模块内部的变量和函数默认是私有的,不会污染全局作用域。这避免了不同代码块之间的命名冲突。
可重用性: 模块可以在多个地方重复使用从而减少代码冗余。例如在Python中可以创建一个包含多个数学运算函数的math_tools模块然后在不同项目中导入和使用这些函数。
可维护性: 通过将代码逻辑分离到不同的模块中,可以提高代码的可读性和可维护性。每个模块职责明确,修改和扩展也更加方便
## 接口
### 初始化导出
```c
#define init_export_hardware(func) __initialize(func, "1")
#define init_export_driver(func) __initialize(func, "2")
#define init_export_system(func) __initialize(func, "3")
#define init_export_module(func) __initialize(func, "4")
#define init_export_app(func) __initialize(func, "5")
```
init模块支持5种不同级别的初始化导出唯一区别就是初始化函数的执行先后而已。
使用例子:
```c
void test_init_hardware(void)
{
printf("hardware init!\r\n");
}
init_export_hardware(test_init_hardware);
void test_init_driver(void)
{
printf("driver init!\r\n");
}
init_export_driver(test_init_driver);
void test_init_system(void)
{
printf("system init!\r\n");
}
init_export_system(test_init_system);
void test_init_module(void)
{
printf("module init!\r\n");
}
init_export_module(test_init_module);
void test_init_app(void)
{
printf("app init!\r\n");
}
init_export_app(test_init_app);
void test_init_system1(void)
{
printf("system1 init!\r\n");
}
init_export_system(test_init_system1);
```
一般是在函数结束下一行导出,然后在主函数特定位置调用`init_execute()`, 程序就会在执行到`init_execute()`时候,按初始化等级进行先后调用初始化函数。