首页 > 解决方案 > 如何从mingw、c++(或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

标签: c++cmingw

解决方案


从评论中得到灵感,我发现了这个问题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

谢谢您的帮助!


推荐阅读