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



在重写内核驱动程序时,我收到以下警告:

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

阅读当我在 {} 中声明一个结构的字段时出现此警告:

struct random_struct test = {
{ .name = "StackOverflow" },
{ .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);
};

如何修复此警告?高通内核使用 -Werror 标志构建,因此此警告至关重要。

static struct device_attribute *opalum_dev_attr表示将opalum_dev_attr声明为指向结构device_attribute的静态指针

您的代码正在尝试初始化结构device_attribute的静态数组

你想要的是: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}, };
} 

最新更新