【问题标题】:Incomplete definition when using struct in header file在头文件中使用结构时定义不完整
【发布时间】:2020-02-11 15:54:38
【问题描述】:

当我尝试在没有functions.hfunctions.c 文件中的结构的情况下编译这个程序时,它可以工作。但是当使用结构时,它不起作用。

如何正确使用这些 .h.c 文件的结构?

ma​​in.c 文件

    #include <stdlib.h>
    #include <stdio.h>
    #include "functions.h"

    int main(void) {
      func1();
      func2();
      //make a linked list of persons

      person * head = NULL;
      head = (person *) malloc(sizeof(person));
      if (head == NULL) {
          return 1;
      }
      head->val = 1;
      head->next = NULL;

      return 0;
    }

functions.h 文件

struct node;  
typedef struct node person;
void func1(void);
void func2(void);

functions.c 文件

 #include "functions.h"

    struct node {
        char name;
        int age;
        node *next;
    };

    void func1(void) {
        printf("Function 1!\n");
    }

    void func2(void) {
        printf("Function 2!\n");
    }

编译:

gcc -o main.exe main.c functions.c

【问题讨论】:

  • 直接在头部定义结构体。
  • 你需要 functions.cmalloc(sizeof(struct node)) 因为只有它知道大小。

标签: c gcc struct compilation header


【解决方案1】:

当您不需要知道类型的大小或“内容”时,您只能使用 opaque 类型(不完整类型)——这意味着当您只需要指向该类型的指针时,您只能使用 opaque 类型。如果您需要大小,例如 main() 当您尝试为一个人分配足够的空间时,那么您不能使用 opaque 类型。

要么在functions.c 中创建分配器函数,在functions.h 中声明它并在main.c 中调用它,要么在functions.h 中定义类型以用于main.cfunctions.c

在您的代码中,main() 函数还访问结构的成员(head-&gt;valhead-&gt;next),因此在 functions.h 中定义类型是最合适的。

【讨论】:

    【解决方案2】:

    添加到functions.h:

    typedef struct node {
            char name;
            int age;
            node *next;
        } person;
    

    Jonathan Leffler 发布的functions.h 成功了!

    从 functions.h 文件中删除:

    struct node;  
    typedef struct node person;
    

    从 functions.c 文件中删除:

    struct node {
        char name;
        int age;
        node *next;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-26
      • 2013-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多