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

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

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

char *s = "constant string";

或者像这样调用函数:

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

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


当前回答

只需使用g++的-w选项。

例子:

g++ -w -o simple.o simple.cpp -lpthread

记住,这并不能避免弃用。相反,它阻止在终端上显示警告信息。

现在,如果你真的想避免弃用,可以像这样使用const关键字:

const char* s = "constant string";  

其他回答

使用-Wno-deprecated选项可以忽略已弃用的警告消息。

任何传递字符串字面量“I am a string literal”的函数都应该使用char const *作为类型,而不是char*。

如果你要修理什么东西,就把它修好。

解释:

你不能使用字符串字面量来初始化将要被修改的字符串,因为它们的类型是const char*。放弃constness以稍后修改它们是未定义的行为,因此您必须将您的const char* strings char by char复制到动态分配的char*字符串中,以便修改它们。

例子:

#include <iostream>

void print(char* ch);

void print(const char* ch) {
    std::cout<<ch;
}

int main() {
    print("Hello");
    return 0;
}

取代

char *str = "hello";

with

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

或者如果你在调用函数:

foo("hello");

将其替换为

foo((char*) "hello");

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

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

之后你可以…

#pragma GCC diagnostic pop

我也遇到过类似的问题,我是这样解决的:

#include <string.h>

extern void foo(char* m);
 
int main() {
    // warning: deprecated conversion from string constant to ‘char*’
    //foo("Hello");
   
    // no more warning
    char msg[] = "Hello";
    foo(msg);
}

我没有访问foo,以适应它接受const char*,这将是一个更好的解决方案,因为foo没有改变m。