![](/img/trans.png)
[英]Setting PYTHONPATH environment variable in Visual Studio C++
[英]Proper setting a local environment variable in C++
在我的代碼中,我使用以下內容:
putenv("TZ=UTC");
tzset();
設置時區。
putenv()
聲明( 這個答案建議它設置環境變量):
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 ++中設置環境變量的正確方法是什么?
字符串文字是const
,它的類型是const char[]
(對於"TZ=UTC"
它將是const char[7]
,包括尾隨空字符'\\0'
),它不能直接分配給a來自C ++ 11的(非const) char*
。
你可以為它構造一個新的char
數組。
char str[] = "TZ=UTC"; // initialize a char array, which will contain a copy of the string "TZ=UTC"
putenv(str);
putenv
通常允許在調用putenv之后更改字符串,並且實際上會自動更改環境。 這就是原型聲明char *
而不是const char *
,但系統不會更改傳遞的字符串。
所以這是const cast
一個罕見的正確用例:
putenv(const_cast<char *>("TZ=UTC"));
或者,您可以使用setenv
const char *
參數的setenv
:
setenv("TZ", "UTC", 1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.