Set local environment variables in C++


How do I set an environment variable in C++?

  • They do not need to persist past program execution
  • They only need to be visible in the current process
  • Preference for platform independent but for my problem only needs to work on Win32/64


5/22/2009 8:20:08 PM

Accepted Answer


       putenv - change or add an environment variable


       #include <stdlib.h>

       int putenv(char *string);

       The  putenv()  function adds or changes the value of environment
       variables.  The argument string is of the form name=value.  If name does
       not already exist in the environment, then string is added  to  the
       environment.   If name does exist, then the value of name in the
       environment is changed to value.  The string pointed to by string becomes
       part of the environment, so altering the string changes the environment.

On Win32 it's called _putenv I believe.

See SetEnvironmentVariable also if you're a fan of long and ugly function names.

6/8/2012 4:45:33 PM

I'm not positive environment variables are what you need, since they aren't going to be used outside of this run of the program. No need to engage the OS.

You might be better off having a singleton class or a namespace that holds all these values, and initialize them when you start the program.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow