将container_of宏应用于嵌入式char数组时报告警告 [英] Report warning when apply container_of macro to embedded char array

查看:109
本文介绍了将container_of宏应用于嵌入式char数组时报告警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将 container_of 宏应用于包含char数组的C结构时,我得到警告:从不兼容的指针类型进行初始化.

When I apply container_of macro to a C struct which contains an array of char, I got warning: initialization from incompatible pointer type.

以下是代码:

#define container_of(ptr, type, member) ({          \
    const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
    (type *)( (char *)__mptr - offsetof(type,member) );})


struct st {
    int a;
    char b;
    char c[16];
    void *p;
};

int main(void)
{
    struct st t = {
        .a = 101,
        .b = 'B',
        .c = "hello",
        .p = NULL
    };

    char (*p)[16] = &t.c;
    struct st *s = container_of(p, struct st, c);

    return 0;
}

看来 __ mptr 的类型是 [] ,这是由 typeof()推论得出的.但是, ptr 本身是(*)[] 类型.显然,它们是不一样的.

It seems that the type of __mptr is [], which is deduced by typeof(). However, ptr itself is type (*)[]. Obviously, they are not the same.

此外,如果我通过 clang 编译此代码,则一切正常.GCC似乎对类型检查有更严格的规则.

Besides, if I compile this code by clang, everything is OK. GCC seems have a more strict rule for type checking.

问:如何更正此警告?

推荐答案

数组类型本身不是 const ,实际上 const ness来自每个单独的成员,而 const .实际上,没有语法允许您声明数组本身是 const .您可以阅读这篇文章以了解更多详细信息.

An array type is itself not const, the constness is actually from each individual member being const. There is actually no syntax allowing you to declare that an array itself is const. You can read this post for additional details.

但是,似乎GCC中的 typeof 宏扩展存在缺陷,因为如果 typeof 解析为数组类型,则 const 限定词适用于数组,而不适用于其单个成员.(AndréSassi 指出此问题似乎已在较新版本的GCC中得到解决.)

It seems, however, that the typeof macro extension in GCC is flawed in that if typeof resolves to an array type, the const qualifier applies to the array rather than to its individual members. (André Sassi has noted this issue seems to have been resolved in a newer version of GCC.)

我不知道您认为可接受的解决方法是什么,但是以下内容在未显示警告的情况下进行了编译.

I don't know what you would consider an acceptable workaround, but the following compiles without the noted warning.

const struct st *ct = &t;
typeof(ct->c) *p = &ct->c;
struct st *s = container_of(p, struct st, c);

这篇关于将container_of宏应用于嵌入式char数组时报告警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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