Proper setup of local environment variable in C ++

In my code, I use the following:

putenv("TZ=UTC");
tzset();

to set the time zone.

Declaration putenv()( this answer recommended setting an environment variable):

int putenv(char *string);

In the assembly, I use the set compiler flags -Wall -Wextra -Werror -std=c++0x, and because of this, I get an error:

timeGateway.cpp:80:18: error: ISO C++ forbids converting a string constant to 'char*' [-Werror=write-strings]
   putenv("TZ=UTC");
                  ^

I know that this error can be suppressed using:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wwrite-strings"
  putenv("TZ=UTC");
#pragma GCC diagnostic pop

But it is very ugly.

My question is: what is the correct way to set an environment variable in C ++?

+4
source share
2 answers

putenv putenv . char * const char *, .

, const cast:

putenv(const_cast<char *>("TZ=UTC"));

setenv, const char *:

setenv("TZ", "UTC", 1);
+3

const, const char[] ( "TZ=UTC" const char[7], '\0'), ( const) char* ++ 11.

char.

char str[] = "TZ=UTC"; // initialize a char array, which will contain a copy of the string "TZ=UTC"
putenv(str);
+8

Source: https://habr.com/ru/post/1651517/


All Articles