在文件范围内,我可以使用初始化(静态)变量的前向声明。存在循环依赖。 s[0]
指的是count
的地址。 count
是指 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]);
如图this StackOverflow question不可能在函数(或 block )范围内使用相同的结构。
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
。这是必不可少的,因为不应在每次调用时都构建数组。
最佳答案
您可以简单地不重新定义它,而是为其分配值:
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
的死店
关于c - "redeclaration of symbol with no linkage"在函数作用域上使用时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18588483/