12

After testing on msvc8, I found:

  1. Parse GetCommandLine() to argc and argv
  2. Standard C Library initialization
  3. C++ Constructor of global variables

These three things are called before entering main().

My questions are:

  1. Will this execution order be different when I porting my program to different compiler (gcc or armcc), or different platform?
  2. What stuff does Standard C Library initialization do? So far I know setlocale() is a must.
  3. Is it safe to call standard C functions inside C++ constructor of global variables?
MikimotoH
  • 393
  • 1
  • 4
  • 16

2 Answers2

5

1: Will this execution order be different when I porting my program to different compiler (gcc or armcc), or different platform?

Yes.

2: What stuff does Standard C Library initialization do? So far I know setlocale() is a must.

I am sure there is other stuff. You should not rely on any global objects util after main has started. This means things like std streams (std::cin, std::cout) may not be usable.

3: Is it safe to call standard C functions inside C++ constructor of global variables?

Probably not.

Martin York
  • 257,169
  • 86
  • 333
  • 562
  • 1
    @ephemient: Probably safe. But probably not a good idea. These streams use the locale another global variable but its value may or may not be the current locale or "C". The unspecified order is not a real problem (if you know it exists (Its just an annoyance that can be worked around (it is a problem if you don;t know it exists))). – Martin York Jan 11 '11 at 00:38
5

Here's an article from the LSB (Linux Standard Base) effort describing what __libc_start_main might do on Linux.

Specifically:

* performing any necessary security checks if the effective user
  ID is not the same as the real user ID.
* initialize the threading subsystem.
* registering the rtld_fini to release resources when this dynamic
  shared object exits (or is unloaded).
* registering the fini handler to run at program exit.
* calling the initializer function (*init)().
* calling main() with appropriate arguments.
* calling exit() with the return value from main().

And here's a more detailed explanation.

This is definitely different to Windows.

  • And that's not even getting into what the C++ runtime library does! – ephemient Jan 11 '11 at 00:30
  • 1
    Being a C++ user hurts my head enough, without trying to look at an implementation of the C++ runtime library... –  Jan 11 '11 at 00:33