Initialising data when application initialises?
What's the best way to initialise [static] data when the main thread of an application initialises?
Here's what I mean: Let's suppose I am writing an api function which needs to work with some static data. Ideally this needs initialising only once. An example would be some check sum routine--here's some psuedo code to demonstrate:
What I want to happen is for this function to be called automatically on initialisation, so as to initialise the static data. This is only an example--I also want (in general) to initialise heap data, so I really do want to know how to call initialisation functions when the main thread starts so as to avoid thread race conditions in the initialisation of data. Another example of use would be the initialisation of singletons.
unsigned int calc_crc32(void* buf, size_t buf_sz)
int rslt = 0;
// Static table
static unsigned char s_table;
static bool s_init = false;
// Initialise static table
if (s_init == false)
s_init = true;
// Calc result
if (buf != 0)
rslt = some_rslt;
Now I know I can put a dummy variable in a cpp file and initialise it from the function, like so:
But this forces me to use a dummy value in order to call c_calc_crc32() at start-up.
// Some cpp file
static int s_dummy = calc_crc32(0, 0);
Is there some way I can ensure calc_crc32 (or a function in general) is called in the main thread when it starts up, without having to use dummy data? And without having to call the function from main--assume I writing api.
Any other suggestions?