c - 如何正确解决 -Wcast-qual

标签 c gcc gcc-warning

我有一个类型为 const char * 的变量 k,以及一个带有原型(prototype)的 glib 函数

void g_hash_table_replace(GHashTable *hash_table,
                          gpointer key,
                          gpointer value);

gpointer 简单定义为

typedef void* gpointer;

我知道在这种情况下,实际上可以将 k 作为 g_hash_table_replace 中的键传递,但是 gcc 给我错误

service.c:49:3: warning: passing argument 2 of ‘g_hash_table_replace’ discards ‘const’ qualifier from pointer target type [enabled by default]
/usr/include/glib-2.0/glib/ghash.h:70:13: note: expected ‘gpointer’ but argument is of type ‘const char *’

这是 gcc 4.6.0。在 4.5.0 及更早版本中,对 (char *) 的简单强制转换就足以抑制此警告,但 gcc 似乎变得“更聪明”了。我试过 (char *)(void *)k,但它仍然知道该变量最初是 const。在 k 上不调用 strdup(3) 来消除此警告的最佳方法是什么?

最佳答案

我刚刚用 gcc 4.6.1 试过了。

#include <glib/ghash.h>
#include <stdio.h>
#include <unistd.h>

const char *k="Testing";

int main(int argc, char **argv)
{

    int val = 1024;

    GHashTable *hash_table=NULL;
    g_hash_table_replace(hash_table,(gpointer) (intptr_t)k, &val);

    return 0;
}

没有强制转换,错误如您上面所述。但是,如果我首先将 const char* 转换为 intptr_t,如上所示,警告将被抑制。您能否确认您仍然遇到我的代码示例的错误?

关于c - 如何正确解决 -Wcast-qual,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6647195/

相关文章:

c++ - 仅使用按位运算符复制 for 循环的功能

c - 在 C 中将字符串转换为十六进制时遇到问题

c - 如何修复使用 gcc 作为编译器的 C 程序的计时 fatal error ?

c - GNU mingw 编译器错误 : sh: gcc: command not found

c - 警告 : incompatible implicit declaration of built-in function ‘xyz’

c - 使用系统调用后重置(stty raw)

c - 在 C 中从管道读取

C: 使一个类型与任何其他类型不兼容

c++11 to_string 与 code::blocks -std=c++11 flag already selected

c++ - 修复 GCC 中的 "comparison is always false ..."警告