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

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

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

char *s = "constant string";

或者像这样调用函数:

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

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


当前回答

而不是:

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

如此:

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

其他回答

只使用类型转换:

(char*) "test"

看看这个情况:

typedef struct tagPyTypeObject
{
    PyObject_HEAD;
    char *name;
    PrintFun print;
    AddFun add;
    HashFun hash;
} PyTypeObject;

PyTypeObject PyDict_Type=
{
    PyObject_HEAD_INIT(&PyType_Type),
    "dict",
    dict_print,
    0,
    0
};

注意名称字段。使用gcc时,它编译时没有警告,但在g++中会。我不知道为什么。

取代

char *str = "hello";

with

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

或者如果你在调用函数:

foo("hello");

将其替换为

foo((char*) "hello");

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

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

测试字符串是const字符串。所以你可以这样求解:

char str[] = "Test string";

or:

const char* str = "Test string";
printf(str);