在C++中设置本地环境变量

Jes*_*ogt 41 c c++ manpage

如何在C++中设置环境变量?

  • 他们不需要坚持执行程序
  • 它们只需要在当前过程中可见
  • 平台独立的偏好,但对我的问题只需要在Win32/64上工作

谢谢

ala*_*mar 53

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.

在Win32上它被称为_putenv我相信.

如果您是长而丑陋的函数名称的粉丝,请参阅SetEnvironmentVariable.

  • 我们可以使用正确的C++标题名称吗?<cstdlib>是合适的(是的,我知道......这是我的一个僵局). (26认同)
  • stlib.h是一个合适的C头文件 - 问题标记为C. (7认同)
  • SetEnvironmentVariable 肯定不是一个丑陋的函数名;它比 putenv 更具描述性。 (5认同)
  • 提问者注意 - Win32中也支持putenv. (4认同)
  • 这是C作为主上帝的意图. (4认同)
  • MSDN明确指出_putenv()仅适用于当前进程.显然,它也只适用于C运行时库可见的环境,但创建新进程的CRT函数都将CRT的环境提供给新进程,因此您通常不会注意到.SetEnvironmentVariable()操纵实际的进程环境表.我不知道这种区别在实践中是否重要.要进行全局环境更改,您必须触摸注册表,这样才难以做到. (2认同)

小智 9

还有setenv,它比 稍微灵活一些putenv,它会setenv检查环境变量是否已经设置并且不会覆盖它,如果您设置了“overwrite”参数表明您不想覆盖它,并且因为名称和值是单独的参数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.
Run Code Online (Sandbox Code Playgroud)

我并不是说其中一个比另一个更好或更差;我只是说其中一个比另一个更好。这仅取决于您的应用程序。

请参阅http://man7.org/linux/man-pages/man3/setenv.3.html