简体   繁体   English

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

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

I am writing a program that needs to set environment variables for the current process from mingw (to be available for subprocesses when using system(...) -call).我正在编写一个程序,该程序需要从 mingw 为当前进程设置环境变量(在使用system(...) -call 时可用于子进程)。

I know how to do in linux, and windows with msvc and clang.我知道如何在 linux 和 windows 中使用 msvc 和 clang。 However, I cannot find any goood examples on how to do it with mingw-g++ .但是,我找不到任何关于如何使用mingw-g++ 的好例子。

How do I implement functions that has this kind of behaviour?如何实现具有这种行为的函数?

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

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

If you want to answer in c, feel free to omit std::string:)如果您想在 c 中回答,请随意省略 std::string :)

Edit:编辑:

When using setenv (the linux way) i get:使用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

When using _putenv_s (the way i have used for msvc and clang on windows) I get.当使用 _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

With inspirations from the comments i found this question on putenv从评论中得到灵感,我在putenv上发现了这个问题

and managed to whip together this prototype application:并设法将这个原型应用程序拼凑在一起:


#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;
}

Resulting output:结果 output:

....
x=10

Thanks for the help!谢谢您的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM