我正在处理一个非常大的代码库,最近升级到GCC 4.3,现在触发了这个警告:

警告:不赞成将字符串常量转换为' char* '

显然,解决这个问题的正确方法是找到每一个声明

char *s = "constant string";

或者像这样调用函数:

void foo(char *s);
foo("constant string");

让它们成为const char指针。但是,这意味着至少要接触564个文件,这不是我目前希望执行的任务。现在的问题是我正在使用-Werror运行,所以我需要一些方法来抑制这些警告。我该怎么做呢?


当前回答

取代

char *str = "hello";

with

char *str = (char*)"hello";

或者如果你在调用函数:

foo("hello");

将其替换为

foo((char*) "hello");

其他回答

当将字符串常量传递给函数时,将其写成:

void setpart(const char name[]);

setpart("Hello");

除了const char name[],你也可以写const char \*name。

它为我消除了这个错误:

[Warning] deprecated conversion from string constant to 'char*' [-Wwrite-strings]

我不明白如何应用你的解决方案:(- kalmanIsAGameChanger

在使用Arduino草图时,我有一个函数引起了我的警告。

最初的功能:

char StrContains(char *str, char *sfind)

为了停止警告,我在char *str和char * find前面添加了const。

修改:

char StrContains(const char *str, const char *sfind).

所有的警告都消失了。

从常量字符串到字符指针进行类型转换。

char *s = (char *) "constant string";

我不能使用编译器开关。所以我把这个:

char *setf = tigetstr("setf");

:

char *setf = tigetstr((char *)"setf");

在c++中,替换:

char *str = "hello";

:

std::string str ("hello");

如果你想比较一下:

str.compare("HALLO");