【问题标题】:gcc: Undeclared variables in C, but they are declaredgcc:C中未声明的变量,但已声明
【发布时间】:2013-11-25 03:16:21
【问题描述】:

下面是我正在编写的 C 程序的第一部分。然而,gcc 在编译期间抛出错误,大意是 setps1 都未声明,但它们已声明。我在这个文件中的每个函数都有这个问题,我不知道出了什么问题。我需要怎么做才能解决问题?

这个函数的具体错误:

a9.c: In function `makeaset':
a9.c:23: error: `set' undeclared (first use in this function)
a9.c:23: error: (Each undeclared identifier is reported only once
a9.c:23: error: for each function it appears in.)
a9.c:23: error: `p' undeclared (first use in this function)
a9.c:34: error: `s1' undeclared (first use in this function)

还有代码sn-p:

#include <stdio.h>
#include <stdlib.h>
#define SIZE 32

struct set {
    char *data;
    int count;
};
typedef struct set set;

void makeaset(set **s1)
{
    int i;
    set *p;
    p = NULL;
    p = malloc(sizeof(set));
    if (p) {
        p->data = malloc(SIZE);
        if (p->data) {
            for (i = 0; i < SIZE; i++)
                p->data[i] = 0;
            p->count = 0;
        }
    }
    *s1 = p;
}

【问题讨论】:

  • 您的类型的名称空间 (struct set) 似乎与您的变量名称空间 (set) 发生冲突。为您的编译器和阅读您的代码的人推荐不同的名称。
  • 正如@chux 所说,尝试typedef struct set set_t; 并将set *p; 更改为set_t *p
  • 就像抽查一样:这段代码在 gcc 4.2.1 中编译得很好。你用的是什么版本?
  • 3.4.3 是安装在我正在使用的服务器上的版本。一些更新会很好。 :) 谢谢你的信息!
  • 您发布的代码 sn-p 是完全合法的。使用 gcc 4.7.2 和 gcc -std=c99 -pedantic -Wall -Wextra(也使用 -std=c90-std=c11)对我来说它编译时没有错误。此外,您的“sn-p”是 26 行,但您在第 34 行报告错误消息。请(a)复制并粘贴您自己的 sn-p 并编译它(我预测它也会为您编译而不会出错) 和 (b) 发布一个 exact 独立源文件,该文件显示错误。您接受的答案不正确。

标签: c variables gcc


【解决方案1】:

试试

struct set_struct {
    char *data;
    int count;
};
typedef struct set_struct set;

或类似的东西。

【讨论】:

  • 是吗?使用它的次数不计其数。不太确定,需要检查标准。
  • _ 开头的名称或以_t 结尾的类型可能会违反其他标准。最好为应用程序使用有意义的名称。
  • 这正是问题所在,现在已经解决。谢谢!
  • 不,typedef struct set set 是完全合法的。不需要区分结构标记和 typedef 名称,因为它们位于不同的命名空间中(不是 C++ 意义上的 namespaces)。
  • @keltar:我认为问题在于 OP 没有向我们展示触发错误消息的实际来源。 (“sn-p”有 26 行,但第 34 行有错误。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多