使用子进程可见的 c++ 在 Windows 中设置环境变量
Set environment variable in Windows with c++ that is visible to subprocess
我想知道如何从 C++ 程序设置环境变量。我有一些要求。
- 它需要对使用 std::system()
启动的子进程可见
- 需要在windows
工作
- 它需要与 std::string
良好的接口
虚拟应用程序示例
void setVariable(std::string name, std::string value) {
// This is what I dont know how to do.
}
int main(int, char **) {
setVariable("hello", "there");
system("echo %hello%");
}
我已经尝试过 _putenv
,但是我的子进程在设置变量后似乎没有找到它。而且我没有找到任何示例如何将 std::string
转换为 SetEnvironmentVariable
的输入
你可以设置环境变量 _putenv_s
:
#include <cstdlib>
void setVariable(std::string name, std::string value) {
_putenv_s(name.c_str(), value.c_str());
}
// if you need a wide version:
void setVariable(std::wstring name, std::wstring value) {
_wputenv_s(name.c_str(), value.c_str());
}
int main() {
setVariable("hello", "there");
std::system("echo %hello%");
}
我想知道如何从 C++ 程序设置环境变量。我有一些要求。
- 它需要对使用 std::system() 启动的子进程可见
- 需要在windows 工作
- 它需要与 std::string 良好的接口
虚拟应用程序示例
void setVariable(std::string name, std::string value) {
// This is what I dont know how to do.
}
int main(int, char **) {
setVariable("hello", "there");
system("echo %hello%");
}
我已经尝试过 _putenv
,但是我的子进程在设置变量后似乎没有找到它。而且我没有找到任何示例如何将 std::string
转换为 SetEnvironmentVariable
你可以设置环境变量 _putenv_s
:
#include <cstdlib>
void setVariable(std::string name, std::string value) {
_putenv_s(name.c_str(), value.c_str());
}
// if you need a wide version:
void setVariable(std::wstring name, std::wstring value) {
_wputenv_s(name.c_str(), value.c_str());
}
int main() {
setVariable("hello", "there");
std::system("echo %hello%");
}