c - "redeclaration of symbol with no linkage"在函数作用域上使用时

标签 c gcc

在文件范围内,我可以使用初始化(静态)变量的前向声明。存在循环依赖。 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/

相关文章:

c - 数组的地址和数组地址的地址

c - 想要加入数组,但他们不这样做

c++ - 我如何在链接描述文件中使用存档中的目标文件?

python - 从 Python 中返回 include 和 runtime lib 目录

c - 获取空长度

c - 递归创建目录

c++ - gcc如何静态分配运行时已知长度的数组

c++ - GCC -Wunused-function 不起作用(但其他警告有效)

c - 可以使用静态链接使用的库构建共享库吗?

c - 如何找到数组的大小(从指向第一个元素数组的指针)?