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

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

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

char *s = "constant string";

或者像这样调用函数:

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

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


当前回答

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

void setpart(const char name[]);

setpart("Hello");

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

它为我消除了这个错误:

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

其他回答

取代

char *str = "hello";

with

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

或者如果你在调用函数:

foo("hello");

将其替换为

foo((char*) "hello");

看看这个情况:

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++中会。我不知道为什么。

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

void setpart(const char name[]);

setpart("Hello");

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

它为我消除了这个错误:

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

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

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

char *setf = tigetstr("setf");

:

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