[comp.lang.c++] file initialization

cjmchale@cs.tcd.ie (Ciaran McHale) (04/08/90)

In article <7466@cadillac.CAD.MCC.COM> vaughan@puma.cad.mcc.com (Paul Vaughan) writes:
>I have recently wanted to arrange for a function to be run during the
>initialization of an object module, but C++ (like C, I suppose),
>doesn't allow one to simply call a function at file scope.
>
>foo();                    //syntax error
>
>So, I just made my foo function return an int and did this:
>
>static int bogus = foo();
>
>This works fine, except g++ gives me the warning
>
>std.cc:2: warning: `bogus' defined but not used
>
>I was thinking I might just add some silly code to use bogus, but
>that's getting awfully kludgy.  Is there a better way of doing this
>kind of thing that doesn't involve any bogus variables or produce
>spurious warnings?

Maybe this isn't what you're looking for but it might help. Perhaps you could
organise your module so that it performs "lazy initialisation". Like the
following:


static boolean init = FALSE;

static void
initialise() {
	init = TRUE;	/* very important! */
	... /* code to initialise the module's variables */
}

a_function_in_this_module() {
	if (!init)
		initialise();	/* perform lazy initialisation */
	
	... /* other code */
}

Of course, you're paying the (small) overhead of having to test for
initialisation for every function call. There's also the possibility that when
you/somebody-else-who-is-maintaining-your-code are adding in an extra function
to the module then you'll forget to perform the lazy initialisation.

Regards,
Ciaran.
-------
cjmchale@cs.tcd.ie