Modules
- C programs are structured with the help of modules.
- Each C module must have a header file (.h). The header file is used to include the module.
- The source file (.c) and contains the source code of the module's functions.
- The following table shows the code separation between the source and the header file.
Content | Source File example.c | Header File example.h |
---|---|---|
Header | ||
Global Variables | ||
Local variables | --- | |
Prototypes of Local Functions | --- | |
Global Functions | ||
Local Functions | --- | |
--- |
- The so-called include guard ensures that the header file is only parsed once by the compiler. The name of the include guard refers to the module name. The format
NAME_H_
is typical. - All includes are typically made inside the source file. Include the own header file last.
- All global objects of the module needs to be declared inside the header file. To prevent naming collisions all global object should start with the module name plus underscore. Snake casing is typical for all C variables and functions.
- For global variables the declaration is done inside the header file by adding the keyword
extern
. No values are added to the declaration. - All local C objects are defined by using the keyword
static
. Local variables appear only inside the source file and can only be accessed by this module. That is why no special naming convention is needed. - The prototypes of the local functions are added on top of the source code. The prototypes of the global functions are added to the header file.
- The source code of both global and local functions are added to the source code.
- The closing
#endif
of the include guard should be the last statement in the header file.
Question
Practice using modules in C programs: Use the previous example utilizing the RGB LED and the button. Create two functions: initialization and switching to the next LED. Move these two function to a separate module.