c - -Wcast-qual : cast discards ‘__attribute__((const))’ qualifier from pointer target type

标签 c gcc casting type-conversion

对于代码:

static const char *a = NULL;
abc((char **)&a);

abc 方法定义为:

abc(char** a)

我收到错误(警告被视为错误):

  error: cast discards '__attribute__((const))' qualifier from pointer target type [-Werror=cast-qual]

为了解决这个问题,我添加了:

#ifdef _PTR_CAST_
#define SIZE_T_CAST uintptr_t 
#else
#define SIZE_T_CAST size_t
#endif

我的问题是,api 调用应该是

abc( (char **)(SIZE_T_CAST)&a); or
abc( (char **)(SIZE_T_CAST *)&a);

它不会提示两者,但正确的方法是什么?

最佳答案

首先,宏SIZE_T_CAST是一个糟糕的主意。只需首先使用正确的类型即可。

代码 (char **)(uintptr_t)&a(char **)(void *)&a 可能会工作,尽管 C 不保证标准。

但是,不使用强制转换会是更好的编码风格。相反,制作一个包装函数,例如在头文件中你可以有:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
inline void const_abc(const char ** p)
{
    abc( (char **)p );
}
#pragma GCC diagnostic pop

然后在代码的其余部分中,当您有 const char ** 参数时调用 const_abc

See here有关禁用代码特定部分的警告的更多信息。

关于c - -Wcast-qual : cast discards ‘__attribute__((const))’ qualifier from pointer target type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44279944/

相关文章:

c - 在 C 中一次读取一个字节的文件效率如何?

c - 如何为 C11 U“unicode 文字”正确使用 `__attribute__((format (printf, x, y)))`?

c - 如果全局变量被中断修改,是否真的需要 volatile 修饰符?

Java:发现很长,需要 int

c++ - 为什么C/C++会自动将char/wchar_t/short/bool/enum类型转换为int?

C程序(Linux): get command line output to a variable and filter data

c - 将单精度除法实现为 double 乘法

c++ - Intel vs GCC on constexpr

c# - 要列出的 ListView 项目(字符串)

Python - 将 float 的商安全转换为 int