views:

127

answers:

4

What I really want is, how do I know when each stage of C++ initialization is truly DONE?

There is static initialization where simple things get assigned. Then there's dynamic static initialization where more complicated statics get assigned, which is not defined across 'translation units'. This is kind of horrible, and there are not many easy ways to cope. I use namespaces in places to make an immediate assignment that happens on loading header files, but the flaw here is that this can then be overwritten in one of the initialization phases.

I can set the initialization to be a function which does 'the right thing' but it would be much easier if I could KNOW what 'phase' I am in somehow. So far as I can tell, this is not possible in any way at all, but I am hoping someone out there will have some good news.

I have worked around the issue that was causing this, which was code not used being unexpectedly linked in because it was in the project. It would still be nice to know the answer to this, but I am guessing the answer is 'there is no way to know for sure'.

I edited the question, I don't really want to know main is started per se.

A: 

how about something like this:

bool is_started(bool set_started=false){
  static bool flag = false;
  if(set_started)
     flag=true;
  return flag;
}

main(){
  is_started(true);
}
catwalk
A: 

If your question is about windows, I know you can detect the messagepump from a process has started. This way you know for sure everything is initialized.

Of course this doesn't fly for *nix

Toad
Or for console applications.
Martin York
+3  A: 

I don't get what problem are you trying to solve.

When you build your application, the linker adds the startup code that is the first code to be executed when the OS loads your program in memory. This code will do all the initialization stuff and, when finished, will call your main() function.

If you are talking about replacing this code with your own, you should check the inner details of your compiler/linker (and be very sure you know what are you doing!!).

If your question is about having multiple processes and you need to know if one of the process has started, you should use a proper syncronization mechanism (that can be one of those provided by the underlying OS or one you make your own).

Remo.D
The "initialisation stuff" includes calling constructors and other functions needed to initialise global objects, so it's normal for some of your own code to run before `main()`.
Mike Seymour
A: 

if your running on windows, create a mutex after your done initializing. You can then WaitForSingleOject on that mutex to detect if your program is truly initialized.

Many applications do this to detect if startup was complete and what the other instance of the application is. This is especially true if you want only 1 instance of a program running.

Andrew Keith