varch/doc/init.en.md

68 lines
2.6 KiB
Markdown

### Introduction
Initialization and export modules play a crucial role in program development as they enable code reuse and modular organization. Through initialization and export modules, developers can divide different functions into separate files, reducing code redundancy and improving maintainability and readability. The following will discuss the functions of initialization and export modules and their implementation methods in different programming languages.
**Basic Functions of Modules**
**Encapsulation**: Variables and functions inside a module are private by default and won't pollute the global scope. This avoids naming conflicts between different code blocks.
**Reusability**: Modules can be reused in multiple places, thus reducing code redundancy. For example, in Python, you can create a `math_tools` module that contains multiple mathematical operation functions and then import and use these functions in different projects.
**Maintainability**: By separating the code logic into different modules, the readability and maintainability of the code can be improved. Each module has a clear responsibility, making it more convenient to modify and expand.
### Interface
#### Initialization and Export
```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")
```
The init module supports five different levels of initialization and export, and the only difference lies in the execution order of the initialization functions.
**Example of Use**:
```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);
```
Generally, the export is done on the next line after the function ends. Then, call `init_execute()` at a specific position in the main function. When the program reaches `init_execute()`, the initialization functions will be called in sequence according to the initialization level.