Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!uwm.edu!zaphod.mps.ohio-state.edu!think!mintaka!bloom-beacon!eru!luth!sunic!mcsun!ukc!tcdcs!swift.cs.tcd.ie!csaran!cjmchale From: cjmchale@cs.tcd.ie (Ciaran McHale) Newsgroups: comp.lang.c++ Subject: Re: file initialization Message-ID: <1990Apr8.160907.16128@cs.tcd.ie> Date: 8 Apr 90 16:09:07 GMT References: <7466@cadillac.CAD.MCC.COM> Reply-To: cjmchale@csaran.UUCP (Ciaran McHale) Organization: DSG, Dept. of Comp.Sc., Trinity College, Dublin, Ireland. Lines: 49 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