c++ - 在 C++ 中正确设置局部环境变量

标签 c++ string c++11 environment-variables string-literals

在我的代码中,我使用了以下内容:

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 literalconst,它的类型是 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/

相关文章:

c++ - VC++ 2010 "array is not a member of std"错误

c++ - 在非静态成员函数中使用 C++11 lambda 并调用同一类的静态成员函数

string - VBA从字符串/单元格的开头删除数字

python - Pandas :如果变量为真,则返回特征名称

c++ - std::function 赋值应该忽略返回类型吗?

c++ - 为什么初始化列表允许在 C++ 中缩小类型?

c++ - 无法正确访问我在另一个类的私有(private)区域中声明的类

python - 与 Photoshop 相比,OpenCV Warpaffine 的质量较低

c++ - 带有 GNU/Linux 代码生成工具的 UML

javascript - 将驼峰式文本转换为首字母大写文本