Set environment variables in C

I’m going to make a wild guess here, but the normal reason that these functions appear to not work is not because they don’t work, but because the user doesn’t really understand how environment variables work. For example, if I have this program:

int main(int argc, char **argv)
{
  putenv("SomeVariable=SomeValue");
  return 0;
}

And then I run it from the shell, it won’t modify the shell’s environment – there’s no way for a child process to do that. That’s why the shell commands that modify the environment are builtins, and why you need to source a script that contains variable settings you want to add to your shell, rather than simply running it.

Leave a Comment