Is it safe to use getenv() in static initializers, that is, before main()? Is it safe to use getenv() in static initializers, that is, before main()? unix unix

Is it safe to use getenv() in static initializers, that is, before main()?


I think you can run your program with LD_DEBUG set to see the exact order:

LD_DEBUG=all <myprogram>

EDIT:If you look at the source code of the runtime linker (glibc 2.7), specifically in files:

  • sysdeps/unix/sysv/linux/init-first.c
  • sysdeps/i386/init-first.c
  • csu/libc-start.c
  • sysdeps/i386/elf/start.S

you will see that argc, argv and environ (alias for __environ) are set before any global constructors are called (the init functions). You can follow the execution starting right from _start, the actual entry point (start.S). As you've quoted Stevens "An array of strings called the enviroment is made available when the process begins", suggesting that environment assignment happens at the very beginning of the process initialization. This backed by the linker code, which does the same, should give you sufficient peace of mind :-)

EDIT 2: Also worth mentioning is that environ is set early enough that even the runtime linker can query it to determine whether or not to output verbosely (LD_DEBUG).


Given that both the environment setup and the invoking of the static initializers are functions that the language run-time has to perform before main() is invoked, I am not sure you will find a guarantee here. That is, I am not aware of a specific requirement here that this has to work and that the order is guaranteed prior to main() in, say, the ANSI language and library specifications or anything....but I didn't check to make sure either.

At the same time, I am not aware of a specific requirement that restricts which run-time library functions can be called from a static initializer. And, more to the point, it would feel like a run-time bug (to me) if you couldn't access the environment from one.

On this basis, I vote that I would expect this to work, is a safe assumption, and current data points seem to support this line of reasoning.


In my experience, the C run time library is initialized before the run-time invokes the initializers of your static variables (and so your initializers may call C run time library functions).