来自 gcc 的警告:围绕标量初始值设定项的大括号,如何修复?

Warning from gcc: braces around scalar initializer, how to fix?

在重写内核驱动程序时我收到了这个警告:

msm-cirrus-playback.c:545:2: warning: braces around scalar initializer

请注意,当我在 {} 中声明一个结构的字段时会出现此警告:

struct random_struct test = {
    { .name = "Whosebug" },
    { .name = "StackExchange" },
};

但我的结构在 {} 中有 2-3 个字段:

static struct device_attribute *opalum_dev_attr = {
    {
    .attr->name = "temp-acc",
    .show = opsl_temp_acc_show,
    .store = opsl_temp_acc_store,
    },
    {
    .attr->name = "count",
    .show = opsl_count_show,
    .store = opsl_count_store,
    },
    {
    .attr->name = "ambient",
    .show = opsl_ambient_show,
    .store = opsl_ambient_store,
    },
    {
    .attr->name = "f0",
    .show = opsl_f0_show,
    .store = opsl_f0_store,
    },
    {
    .attr->name = "pass",
    .show = opsl_pass_show,
    },
    {
    .attr->name = "start",
    .show = opsl_cali_start,
    },
};

这个结构:

struct device_attribute {
    struct attribute    attr;
    ssize_t (*show)(struct device *dev, struct device_attribute *attr,
            char *buf);
     ssize_t (*store)(struct device *dev, struct device_attribute *attr,
             const char *buf, size_t count);
};

如何修复此警告? Qualcomm 内核正在使用 -Werror 标志构建,因此此警告很重要。

static struct device_attribute *opalum_dev_attr 表示 将 opalum_dev_attr 声明为指向 struct device_attribute[=13 的静态指针=]

您的代码正在尝试初始化结构 device_attribute

的静态 array

你想要的是:static struct device_attribute opalum_dev_attr[]这意味着声明opalum_dev_attr为结构device_attribute

的静态数组

这是因为你初始化的是指向结构的指针,而不是结构本身。

您需要将引用分配给结构,例如使用复合文字

struct x 
{
    int a,b,c;
}a = {1,2,3};



void foo()
{
    struct x a = {1,2,3};
    struct x *b = {1,2,3}; // wrong warning here
    struct x *x = &(struct x){1,2,3}; // correct reference to the struct assigned (using compound literal
    struct x *y = (struct x[]){{1,2,3}, {4,5,6}, {4,5,6}, };
    struct x z[] = {{1,2,3}, {4,5,6}, {4,5,6}, };

}