Section variables are used widely by the nRF5 SDK modules ( More specifically in libraries) as a way to safely share variables between different independent pieces of code (for example, files or modules) without relying on dynamic memory allocation(
new) , which are absolutely discouraged in embedded systems. The following is derived from nRF5 SDK documentation:
One module, Registrar creates the section that can hold variables.
Other modules (the Registrants) can then create variables to place them into the section at compile time (or more precisely, at link time). Each variable can be accessed by the registrar and the registrant that created it.
Main reasons for using section variables are:
- Avoid using the standard C or C++ allocator (dynamic memory allocation). Standard dynamic memory allocation is forbidden in most embedded C and C++ coding standards such as MISRA C for safety, security, performance and reliability issues.
- Decoupled code: Section variables are declared in the registrant code, without having to change the code of the registrar.
- Transparency: The registrant can access its section variables in the same way as any other variables.
- Access control: Variables can be declared as static by the registrants and still be shared with the registrar.
- Ease of use: The registrar can access all registered variables through macros that are provided by the section variables module.
- No duplication of variables: The variable that is accessed by the registrar is the variable that the registrant created, not a copy.
- Space efficiency: The required storage space is dynamically adjusted at link time, but frozen at run time.
Section variables are implemented through the library
nrf_section available in
<nRF5 SDK Installation Path>\components\libraries\experimental_section_vars. The library
nrf_sectiondoes not control the order of the variables in a section across compiler versions and across compilations. This issue was addressed in the extension which is called section variables iterator (
nrf_section_iter) available in the same directory. Note that the library extension
nrf_section_iteruses a slightly different API.