C中的结构声明

时间:2013-05-02 14:06:46

标签: c struct forward-declaration

我在纯C中有一个简单的程序,用于从文件中读取记录并将其放入链接列表中。我不允许使用全局变量。程序看起来像这样:

Here are some includes
Some #defines

Function headers for list manipulation:
 void add_item(Record * p, LL * ll);
 void print_all(LL * ll);
 void load(LL * ll);
 ...

    int main(int argc, char const *argv[])
    {

        // Sample struct defining one record
        typedef struct Record
        {
            char sign[10];
            long int isbn;
            char name[100];
            char authors[100];
            long int date;
            int id;
            struct Record * next;
        } Record;

        // Information about linked list (LL)
        typedef struct LL
        {
            Record * HEAD;
        }LL;

        // create new Linked List
        LL * ll = (LL *) malloc(sizeof(LL));

        // init 
        ll->HEAD = NULL;

        // Some other work with ll, record ...
}

// now functions its self

// add item p into ll
void add_item(Record * p, LL * ll)
{
    if (ll->HEAD == NULL)
    {
        ll->HEAD = p;
        ll->HEAD->next = NULL;
    }
    else
    {
        Record * cur = ll->HEAD;

        while(cur->next != NULL)
            cur = cur->next;
        cur->next = p;
    }
}

void print_all(LL * ll)
{
    if (!ll->HEAD)
    {
        printf("%s\n", "ll->HEAD is NULL...");
        return;
    }

    Record * cur = ll->HEAD;

    while(cur)
    {
        printf("%s\n", cur->name );
        cur = cur->next;
    }
}

// other functions

现在当我在我的Ubuntu 12.04上使用gcc编译时,我得到了:

project.c:20:15: error: unknown type name ‘Record’
project.c:20:27: error: unknown type name ‘LL’
project.c:21:16: error: unknown type name ‘LL’
project.c:22:11: error: unknown type name ‘LL’
project.c:145:15: error: unknown type name ‘Record’
project.c:145:27: error: unknown type name ‘LL’
project.c:162:16: error: unknown type name ‘LL’
project.c:182:11: error: unknown type name ‘LL’

如何在编译自身并在main()中声明时,如何让编译器知道函数头之前的struct Recordstruct LL

1 个答案:

答案 0 :(得分:4)

你不能。

声明必须在声明函数的同一级别中可见。

将struct声明移到list函数原型之前。

或添加预申报:

typedef struct Record Record;

只要列表函数只处理指针(Record *),这应该有效。