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

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

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

char *s = "constant string";

或者像这样调用函数:

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

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


当前回答

我相信将-Wno-write-strings传递给GCC将抑制此警告。

其他回答

在c++中,替换:

char *str = "hello";

:

std::string str ("hello");

如果你想比较一下:

str.compare("HALLO");

下面是如何在文件中内联完成它,因此您不必修改Makefile。

// gets rid of annoying "deprecated conversion from string constant blah blah" warning
#pragma GCC diagnostic ignored "-Wwrite-strings"

之后你可以…

#pragma GCC diagnostic pop

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

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

取代

char *str = "hello";

with

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

或者如果你在调用函数:

foo("hello");

将其替换为

foo((char*) "hello");

而不是:

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

如此:

void foo(const char s[]);
foo("constant string");