Set local environment variables in C++

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.


There's also setenv, which is slightly more flexible than putenv, in that setenv checks to see whether the environment variable is already set and won't overwrite it, if you set the "overwrite" argument indicating that you don't want to overwrite it, and also in that the name and value are separate arguments to setenv:

NAME
        setenv - change or add an environment variable
SYNOPSIS
       #include <stdlib.h>

       int setenv(const char *name, const char *value, int overwrite);

       int unsetenv(const char *name);

   Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

       setenv(), unsetenv():
           _POSIX_C_SOURCE >= 200112L
               || /* Glibc versions <= 2.19: */ _BSD_SOURCE
DESCRIPTION
       The setenv() function adds the variable name to the environment with
       the value value, if name does not already exist.  If name does exist
       in the environment, then its value is changed to value if overwrite
       is nonzero; if overwrite is zero, then the value of name is not
       changed (and setenv() returns a success status).  This function makes
       copies of the strings pointed to by name and value (by contrast with
       putenv(3)).

       The unsetenv() function deletes the variable name from the
       environment.  If name does not exist in the environment, then the
       function succeeds, and the environment is unchanged.

I'm not saying either is better or worse than the other; it just depends on your application.

See http://man7.org/linux/man-pages/man3/setenv.3.html


NAME

       putenv - change or add an environment variable

SYNOPSIS

       #include &ltstdlib.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.

Tags:

C++

C

Manpage