如何从 mingw、c++(或 c)获取和设置环境变量

How to get and set environment variable from mingw, c++ (or c)

我正在编写一个程序,需要从 mingw 为当前进程设置环境变量(以便在使用 system(...)-call 时可用于子进程)。

我知道如何在 linux 和 windows 中使用 msvc 和 clang。但是,我找不到任何关于如何使用 mingw-g++.

的好例子

如何实现具有这种行为的函数?

// Example usage:
void setVar(std::string name, std::string value) {
    // How to do this
}

std::string getVar(std::string name) {
    // ... and this
}

如果你想用c回答,可以省略std::string :)

编辑:

当使用 setenv(linux 方式)时,我得到:

src/env.cpp: In function 'void appendEnv(std::string, std::string)':
src/env.cpp:46:5: error: 'setenv' was not declared in this scope; did you mean 'getenv'?
   46 |     setenv(name.c_str(), value.c_str(), 1);
      |     ^~~~~~
      |     getenv

当使用 _putenv_s 时(我在 windows 上使用 msvc 和 clang 的方式)我明白了。

src/env.cpp: In function 'int setenv(const char*, const char*, int)':
src/env.cpp:16:12: error: '_putenv_s' was not declared in this scope; did you mean '_putenv_r'?
   16 |     return _putenv_s(name, value);
      |            ^~~~~~~~~
      |            _putenv_r

我从 this question putenv

上的评论中得到灵感

并设法将这个原型应用程序组合在一起:


#include <cstdlib> // For system(...)

#ifdef __MINGW32__
extern int putenv(char *); // Not defined by mingw
#endif

int main() {
    putenv(const_cast<char *>("x=10"));
    system("set"); // Output variables to se if it works

    return 0;
}

结果输出:

....
x=10

感谢您的帮助!