An approach that can sometimes be useful if you need a "reset" method that can hit an unknown number of functions or modules should have a global counter, how many times this reset method has been called, and then each function or module includes code, for example:
extern unsigned long global_reset_count;
void do_something (int whatever)
{
static ... this, that, the other, etc. ...;
static unsigned long my_reset_count;
if (my_reset_count! = global_reset_count)
{
my_reset_count = global_reset_count;
... initialize this, that, the other, etc ...
}
}
In some multi-threaded contexts, if the initialization of static variables may depend on some global variables, you can replace "if" with "while"; in this case; memory locks may also be required in this case, although the exact requirements will vary depending on the operating environment.
In addition, an alternative template that can be useful on embedded systems is to have a global variable modules_initialized , which gets the global method reset 0, and then each module starts with something like:
if (! atomic_bit_test_and_set32 (& modules_initialized, FOOBOZZ_MODULE_ID))
{
... Initialize module FOOBOZZ ...
}
This will require that there are no more than 32 module identifiers, and would require that they be uniquely distributed in some way, but some systems can handle this pretty well. For example, the linker may allow the definition of a โdata sectionโ from address 0-31 of the address space, regardless of any other; if each module declares a single-byte variable in this address space, the linker can generate the corresponding addresses for these variables.
supercat
source share