This is the way I get to prevent funA,funB,funC, etc.. for being used before init
#define INIT_KEY 0xC0DE //any number except 0, is ok
static int initialized=0;
int Init()
{
//many init task
initialized=INIT_KEY;
}
int funA()
{
if (initialized!=INIT_KEY) return 1;
//..
}
int funB()
{
if (initialized!=INIT_KEY) return 1;
//..
}
int funC()
{
if (initialized!=INIT_KEY) return 1;
//..
}
The problem with this approach is that if some of those function is called within a loop
so “if (initialized!=INIT_KEY)” is called again, and again, although it’s not necessary.
It’s a good example of why constructors are useful haha, If it were an object I would be sure that when it was created, initialization was called, but in C, I don’t know how to do it.
Any other ideas are welcome!
Use pointer to function.
At construct time, point the functions at the function
that does the required initialization, then updates the function pointers to point to the actual functions that do the work.
I have done this with arrays of pointer to member functions in a class. The class has an internal integer which says what state the object it in. The integer is used to subscript into the array of pointer to member functions… State 0 does the init. State 1, does the work, State 2 sets things back to state 1.
It worked very cleanly.