显式忽略来自指针目标类型的-Wcast-qual:cast丢弃'__attribute __((const))'限定符 [英] Explicit ignore warning from -Wcast-qual: cast discards ‘__attribute__((const))’ qualifier from pointer target type

查看:1221
本文介绍了显式忽略来自指针目标类型的-Wcast-qual:cast丢弃'__attribute __((const))'限定符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

static char buf[8];
void foo(){
    const char* ptr = buf;
    /* ... */
    char* q = (char*)ptr;
}

上面的代码片段会生成warning:cast discards '__attribute __((const))'限定符来自指针目标类型[-Wcast-qual]。我喜欢 -Wcast-qual ,因为它可以帮助我不小心写入内存,我不应该写信给它。

The above snippet will generate "warning: cast discards ‘__attribute__((const))’ qualifier from pointer target type [-Wcast-qual]". I like -Wcast-qual since it can help me from accidentally writing to memory I shouldn't write to.

但现在我只想抛弃const(仅针对整个文件或项目)。它指向的内存是可写的(就像上面的 buf 一样)。我宁愿不要从 ptr 中删除​​const,因为它在其他地方使用,并且保持指针(一个const和一个非const)似乎是一个糟糕的想法。

But now I want to cast away const for only a single occurrence (not for the entire file or project). The memory it is pointing to is writable (just like buf above). I'd rather not drop const from ptr since it is used elsewhere and keeping to pointers (one const and one non-const) seems like a worse idea.

推荐答案

在GCC 4.2和更高版本中,您可以使用#pragma来禁止函数的警告。缺点是你必须在整个功能上压制警告;您不能仅仅将它用于某些代码行。

In GCC 4.2 and later, you can suppress the warning for a function by using #pragma. The disadvantage is you have to suppress the warning across the whole function; you cannot just use it only for some lines of code.

#pragma GCC diagnostic push  // require GCC 4.6
#pragma GCC diagnostic ignored "-Wcast-qual"
void foo(){
    const char* ptr = buf;
    /* ... */
    char* q = (char*)ptr;
}
#pragma GCC diagnostic pop   // require GCC 4.6

是你的整个项目可以使用相同的警告/错误检查选项。而且你确切地知道代码的作用,并且让GCC忽略对某段代码的明确检查。

由于这个编译指示的限制,你必须从当前函数中提取基本代码到新的一个,并使用#pragma单独创建新功能。

The advantage is your whole project can use the same warning/errors checking options. And you do know exactly what the code does, and just make GCC to ignore some explicit checking for a piece of code.
Because the limitation of this pragma, you have to extract essential code from current function to new one, and make the new function alone with this #pragma.

这篇关于显式忽略来自指针目标类型的-Wcast-qual:cast丢弃'__attribute __((const))'限定符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆