2

我有他们的头文件附带的这两个结构。

我的结构编号 1 是:

头文件'list.h':

typedef struct list * List;

源文件“list.c”:

struct list {
    unsigned length;
    char * value;
};

我的结构号 2 是:

头文件“bal.h”:

typedef enum {START, END, MIDDLE, COMMENTS, CONDITIONS} TypeListBal;
typedef struct bal * Bal;

源文件“bal.c”:

i've include those header files : 
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include "list.h"

struct bal {
    TypeListBal type;
    List name;              // Name of the bal
    List attributes[];          // Array of type struct List
};

当我尝试在我的 bal.c 文件中使用一个函数时,例如:

Bal createBal(List name){

char * search;
const char toFind = '=';
    search = strchr(name->value, toFind);

}

我在这一行遇到错误:search = strchr(name->value, toFind); 说:错误:取消引用指向不完整类型的指针

我不知道为什么因为我已经在我的 bal.c 中包含了 list.h

我在 Stackoverflow 上读过很多书,说这种类型的程序被称为:不透明类型,这似乎非常好,但我不知道如何将我的其他头文件用于其他源文件。我认为我所要做的就是将我的 list.h 包含在我的 bal.c 文件中。

我正在用这个 commamd 在 gcc 中编译:gcc -g -W -Wall -c bal.c bal.h

非常感谢你 !

4

2 回答 2

3

.h 文件只有 和 的struct声明typedef

typedef struct list * List;

这并没有提供任何关于成员是什么的线索struct。它们被“隐藏”在 .c 文件中。当编译器编译bal.c时,它无法知道struct list有一个成员value

您可以通过以下几种方式解决此问题:

  1. 将 的定义struct list也放入 .h 文件中。
  2. 提供可以获取/设置struct list对象值的函数。
于 2015-04-09T02:38:37.543 回答
1

当您包含头文件时,这就是您所做的一切。在您的头文件中,您只有以下行:

typedef struct list * List;

尝试从 main 使用这个结构会导致编译器抱怨类型不完整,因为从源文件的角度来看,这个结构没有成员。事实上,它根本没有定义。

你需要把:

struct list;
typedef struct list * List;

在你的头文件中。但是,请注意,此过程会创建一个不透明的结构!这意味着做例如

List l1;
l1->data = 0; //error

不允许,因为编译器只能看到头文件中包含的内容。在该编译单元中,结构中不存在变量。

可以有意使用,以强制用户为您的数据类型通过 getter/setter。就像是

int data = ListStuff_Get_Item1(l1);

可以,但是ListStuff_Get_Item1()函数需要在.h中声明,在.c中定义。

于 2015-04-09T02:42:39.620 回答