c++ - 如何从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
解决方案
从评论中得到灵感,我发现了这个问题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
谢谢您的帮助!
推荐阅读
- php - 跨 2 列的 PostgreSQL 10 约束?
- tensorflow - 在 Google ML 上运行对象检测 API 时出错
- symfony - 使用 FR3DLdapBundle 和 FOSUserBundle 与 Symfony 2.8 的 SQL 错误
- ethereum - 合约地址冲突
- ios - 如何在 swift 中使用 UIButton 操作添加多个 UITextField
- python - STL 分解 Python - 绘制图表,值为 N/A
- wordpress - 根据运输方式,使用 woocommerce 删除选定的结帐字段
- regex - 如何配置 Jenkins 以去除 git 分支参数中的前导“origin/”?
- c# - 在退出事件之前发送 TextBox KeyEventArgs 值
- nwjs - 在 Mac 上使用 nwjs 硬刷新浏览器