Why does my compiler not recognise a typedef in another included header file?

I have a problem where the compiler (linker?) does not seem to detect a typedef in another included header file. I have two header files:

// ConstantsVariables.h

#ifndef CONSTANTSVARIABLES_H
#define CONSTANTSVARIABLES_H
#include "CellList.h"

extern double boxLength_x, boxLength_y;

typedef struct Position {
    double x;
    double y;
} Position;

typedef struct Particle {
    Position position;
    int inWhichCell;
    double localOrientation;
    double initialAngle;
    double rotatedAngle;
    int insideGrain;
} Particle;

#endif /* CONSTANTSVARIABLES_H */

and

// CellList.h

#ifndef CELLLIST_H
#define CELLLIST_H
#include "ConstantsVariables.h"

typedef struct Cell {
    int numParticles;
    Particle **particles;
} Cell; 

typedef struct CellList {
    int numCols, numRows, numCells;
    double cellLength_x, cellLength_y;
    Cell *cells;
} CellList;

CellList *createCellList(void);
void destroyCellList(CellList *cellList);

#endif /* CELLLIST_H */

with matching .c files that implement the CellList functions and definitions for boxLength_x/y. However, when I try to compile my main file, which has these headers included and uses the variables/functions in them, I get an error in CellList.h saying unknown type name 'Particle'. What am I missing?

>Solution :

ConstantsVariables.h includes CellList.h before it has typedef … Particle;. CellList.h uses Particle, so Particle is not defined where CellList.h uses it.

Although CellList.h has #include "ConstantsVariables.h", at that point ConstantsVariables.h has already defined CONSTANTSVARIABLES_H, so the #ifndef CONSTANTSVARIABLES_H in ConstantsVariables.h causes the rest of the contents of ConstantsVariables.h not to be processed.

You should design your source and header files to form a tree structure: Each file should include only files “lower” in the tree. (In computer science, tree structures are generally drawn with the root node at the top and leaves toward the bottom.) There should be no loops in the includes.

Nothing in ConstantsVariables.h depends on anything in CellList.h, so there is no need for ConstantsVariables.h to #include "CellList.h" at its beginning. It could be removed.

If you intended ConstantsVariables.h to be some general header file for your project that can be included so that every source file can include it and not pick out individual headers to include, then it should be the file that depends on other headers and other headers should not depend on it. That means CellList.h should not have #include "ConstantsVariables.h". Instead, move the declarations in ConstantsVariables.h to another file, such as one named PositionParticle.h. Inside ConstantsVariables.h, replace the moved declarations with #include PositionParticle.h. In CellList.h, change #include "ConstantsVariables.h" to #include "PositionParticles.h".

Leave a Reply