首页 > 解决方案 > 在头文件中使用结构时定义不完整

问题描述

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

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

main.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;
    }

函数.h 文件

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

函数.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 函数.c

标签: cgccstructcompilationheader

解决方案


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

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

在您的代码中,该main()函数还访问结构 ( head->val, head->next) 的成员,因此定义类型 infunctions.h是最合适的。


推荐阅读