在我的代码中,我使用了以下内容:
putenv("TZ=UTC");
tzset();
设置时区。
putenv()
声明(this answer推荐设置环境变量):
int putenv(char *string);
我正在使用的构建系统设置了编译器标志 -Wall -Wextra -Werror -std=c++0x
并且因此我收到了错误:
timeGateway.cpp:80:18: error: ISO C++ forbids converting a string constant to 'char*' [-Werror=write-strings]
putenv("TZ=UTC");
^
我知道这个错误可以通过使用来抑制:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wwrite-strings"
putenv("TZ=UTC");
#pragma GCC diagnostic pop
但这很丑陋。
我的问题:在 C++ 中设置环境变量的正确方法是什么?
最佳答案
string literal是 const
,它的类型是 const char[]
(对于 "TZ=UTC"
它将是 const char[7]
,包括尾随的空字符 '\0'
),不能从 C++ 直接分配给(非常量)char*
11.
你可以为它构造一个新的 char
数组。
char str[] = "TZ=UTC"; // initialize a char array, which will contain a copy of the string "TZ=UTC"
putenv(str);
关于c++ - 在 C++ 中正确设置局部环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38993254/