9

I work on windows and MacOS, I would like to get environment variables. How to get system environment variables using boost library?

Are there equivalent to System.Environment.GetEnvironmentVariable() from .Net ?

Arman
  • 4,387
  • 10
  • 38
  • 63

2 Answers2

21

There's no need for Boost. Use std::getenv from <cstdlib>, which is a standard C++ function.

Fred Foo
  • 328,932
  • 68
  • 689
  • 800
  • It seems there are no portable system environment variables in boost. FileSystem has a portable file names, but environment variables are not portable: Win7 has HOMEPATH and *NIX has a HOME, same for USERNAME and USER. – Arman Jan 13 '12 at 13:08
  • @Arman: portable homedir finding is relatively useless, since Windows and Unix have very different conventions as to where user-specific data must be stored. – Fred Foo Jan 13 '12 at 13:20
  • Yes I agree, but to store program general options is useful to have some convention: on linux usually user programs are storing $HOME/.myset or windows probably %userprofile%/.myset or something similar. Therefore better to have portable functions. – Arman Jan 13 '12 at 13:36
  • @Arman: you could define a function `get_home` that returns `$HOME` is that's set, `$HOMEPATH` otherwise. – Fred Foo Jan 13 '12 at 13:52
  • 2
    The problem is that std::getenv isn't thread-safe, and there doesn't seem to be a std::dupenv. – snips-n-snails Nov 07 '14 at 00:32
  • 1
    @traal: that's only a problem if you call `setenv` from another thread, right? And having threads communicate through the process environment doesn't sound like a great idea to me... – Fred Foo Nov 07 '14 at 10:13
  • std::getenv is neither reentrant nor thread-safe. Not a good choice. http://stackoverflow.com/questions/4286934/warning-c4996-this-function-or-variable-may-be-unsafe-compared-to-gcc-on-pos – Kevin Johnsrude Sep 13 '16 at 17:32
  • C++ 11 - unlike earlier standard revisions - does guarantee the std::getenv() is thread-safe, as long as no modifications are done to the environment concurrently - see http://en.cppreference.com/w/cpp/utility/program/getenv . – YitzikC Feb 07 '17 at 13:32
  • As for storing user-options in a portable way, you should probably use a higher-level library that provides such functionality through platform-agnostic abstractions, such as [tag:wxwidgets]. – YitzikC Feb 07 '17 at 13:34
4

You probably want a plain c (and ++) getenv() function, it needs not to be boosted.

Michael Krelin - hacker
  • 122,635
  • 21
  • 184
  • 169