对于代码:
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/