Set environment variable in Windows with c++ that is visible to subprocess

I would like to know how to set a envirenment variable from a c++ program. I have some requirements.

  • It needs to be visible to child processes that is being started with std::system()
  • It needs to work in windows
  • It needs to interface nice with std::string

Example dummy application

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%");
}

I have experimented with _putenv, but my subprocess does not seeme to find the variable after it being set. And I do not find any example how to convert std::string to the input for SetEnvironmentVariable

Answer

You can set environment variables with _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%");
}

Leave a Reply

Your email address will not be published. Required fields are marked *