繁体   English   中英

C-头文件中的结构定义

[英]C - struct definition in header files

我有两个结构多数民众赞成在与他们的头文件。

我的结构数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上已经读了很多书,它称这种编程类型为:opaque type,这看起来确实不错,但是我不知道如何将我的其他头文件转换为其他源文件。 我以为我要做的就是在bal.c文件中包含list.h。

我正在使用以下逗号在gcc中进行编译: gcc -g -W -Wall -c bal.c bal.h

非常感谢你 !

.h文件仅具有structtypedef的声明。

typedef struct list * List;

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

您可以通过以下两种方法解决此问题:

  1. struct list的定义也放在.h文件中。
  2. 提供可以获取/设置struct list对象的值的struct list

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

typedef struct list * List;

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

您需要输入:

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中定义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM