簡體   English   中英

使用子進程可見的 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%");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM