Reputation: 311
i have those two struct thats come with their header files.
my struct number 1 is :
header files 'list.h':
typedef struct list * List;
source files 'list.c' :
struct list {
unsigned length;
char * value;
};
my struct number 2 is :
header files 'bal.h' :
typedef enum {START, END, MIDDLE, COMMENTS, CONDITIONS} TypeListBal;
typedef struct bal * Bal;
Source files '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
};
When i'm trying to use a function in my bal.c file like :
Bal createBal(List name){
char * search;
const char toFind = '=';
search = strchr(name->value, toFind);
}
i'm getting an error at this line : search = strchr(name->value, toFind);
saying : error: dereferencing pointer to incomplete type
I dont know why cause i've already include the list.h in my bal.c
I've read a lot over Stackoverflow saying that type of programmation it's called : opaque type which seems to be really nice but i dont get how to use my others headers file into other sources files. I thought that all i have to do it's to include my list.h in my bal.c files.
I'm compiling in gcc with this commamd : gcc -g -W -Wall -c bal.c bal.h
Thanks you very much !
Upvotes: 2
Views: 11839
Reputation: 206577
The .h file only has the declaration of the struct
and the typedef
.
typedef struct list * List;
That doesn't give any clues as to what the members of the struct
are. They are "hidden" in the .c file. When the compiler compiles bal.c
, it has no way of knowing that struct list
has a member value
.
You can resolve this in couple of ways:
struct list
also in the .h file.struct list
object.Upvotes: 3
Reputation: 410
When you include header files, well, that's all you're doing. In your header files you have only the line:
typedef struct list * List;
Trying to use this structure from main causes the compiler to complain about an incomplete type, because from the perspective of the source file, this structure has no members. In fact it's not defined at all.
You need to put:
struct list;
typedef struct list * List;
In your header files. However, note that this process creates an opaque struct! Which means that doing e.g.
List l1;
l1->data = 0; //error
Is not allowed, because the compiler sees only what's included from the header file. In that compilation unit, no variables exist in the structure.
This can be used intentionally, to force users to go through getters/setters for your datatype. Something like
int data = ListStuff_Get_Item1(l1);
Can be done, but the ListStuff_Get_Item1() function needs to be declared in .h, and defined in .c.
Upvotes: 1