tags:

views:

940

answers:

2

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

Thanks

+6  A: 

NAME

   putenv - change or add an environment variable

SYNOPSIS

   #include <stdlib.h>

   int putenv(char *string);

DESCRIPTION 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.

alamar
Note to questioner - putenv is also supported in Win32.
anon
Can we please use proper C++ header names? <cstdlib> is appropriate (yeah, I know...it's a hangup of mine).
Harper Shelby
It is C as a Lord God intended.
alamar
stlib.h is a proper C header file - the question is tagged as C
anon
Are you sure that the change isn't global on Windows ?
Bastien Léonard
"Sets the contents of the specified environment variable for the current process."
alamar
MSDN is explicit that _putenv() only applies to the current process. Apparently, it also only applies to the environment as made visible to the C runtime library, but the CRT functions that create new processes all supply the CRT's environment to the new process so you usually wouldn't notice. SetEnvironmentVariable() manipulates the actual process environment table. I don't know if that distinction matters in practice. To make global environment changes, you have to touch the Registry, so that is much harder to do by accident.
RBerteig
By the way, putenv() is not in the standard C library. It's defined by POSIX. That's why the Microsoft version starts with an underscore (unless you use the #define that enables POSIX functions, in which case oldnames.lib redirects putenv() -> _putenv() for you).
bk1e
+1  A: 

I'm not positive envitonment variables is 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.

JohnMcG
They will only be visible to child processes, and putenv() usually doesn't need to talk to the OS at all.
RBerteig