Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing recursive C #include

I roughly understand the rules with what #include does with the C preprocessor, but I don't understand it completely. Right now, I have two header files, Move.h and Board.h that both typedef their respective type (Move and Board). In both header files, I need to reference the type defined in the other header file.

Right now I have #include "Move.h" in Board.h and #include "Board.h" in Move.h. When I compile though, gcc flips out and gives me a long (what looks like infinite recursive) error message flipping between Move.h and Board.h.

How do I include these files so that I'm not recursively including indefinitely?

like image 423
twolfe18 Avatar asked Jan 11 '10 21:01

twolfe18


1 Answers

You need to look into forward declarations, you have created an infinite loops of includes, forward declarations are the proper solution.

Here's an example:

Move.h

#ifndef MOVE_H_
#define MOVE_H_

struct board; /* forward declaration */
struct move {
    struct board *m_board; /* note it's a pointer so the compiler doesn't 
                            * need the full definition of struct board yet... 
                            * make sure you set it to something!*/
};
#endif

Board.h

#ifndef BOARD_H_
#define BOARD_H_

#include "Move.h"
struct board {
    struct move m_move; /* one of the two can be a full definition */
};
#endif

main.c

#include "Board.h"
int main() { ... }

Note: whenever you create a "Board", you will need to do something like this (there are a few ways, here's an example):

struct board *b = malloc(sizeof(struct board));
b->m_move.m_board = b; /* make the move's board point 
                        * to the board it's associated with */
like image 105
Evan Teran Avatar answered Sep 20 '22 11:09

Evan Teran