1

在文件范围内,我可以使用初始化(静态)变量的前向声明。存在循环依赖。s[0]指的是地址countcount指 中的项目数s

struct s { int *a; };

static int count;
int data1;
static struct s s[] = {
    &count, &data1 // , ... a lot more
};
static int count = sizeof(s) / sizeof(s[0]);

这个 StackOverflow 问题所示,不可能在函数(或块)范围内使用相同的构造。

void foo(void)
{
    static int count;
    static struct s s[] = {
        &count, &data1 // , ... a lot more
    };
    static int count = sizeof(s) / sizeof(s[0]);
}

它导致错误消息

redeclaration of 'count' with no linkage.

目标是定义具有此类表的大量函数。我不愿意在文件范围内定义第二组巨大的变量。有没有办法在函数范围内定义这些变量?

编辑:代码不包括一件重要的事情。我错过了static初始化结构之前的内容。这是必不可少的,因为不应在每次调用时都构建数组。

4

1 回答 1

2

您可以简单地不重新定义它,而是将值分配给它:

void foo(void)
{
    static int count;
    struct s s[] = {
        &count, &data1 // , ... a lot more
    };
    count = sizeof(s) / sizeof(s[0]);
}

差异应该可以忽略不计。或者:

void foo(void)
{
    struct s s[] = {
        NULL, &data1 // , ... a lot more
    };
    static int count = sizeof(s) / sizeof(s[0]);
    s[0].a = &count;
}

编译器甚至可以优化它以初始化s[0].a成员&count并消除它的死存储NULL

于 2013-09-03T11:21:38.413 回答