C - struct definition in header files

Thapipo picture Thapipo · Apr 9, 2015 · Viewed 8.1k times · Source

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 !

Answer

R Sahu picture R Sahu · Apr 9, 2015

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:

  1. Put the definition of struct list also in the .h file.
  2. Provide functions that can get/set the value of a struct list object.