防止递归C#include

two*_*e18 7 gcc include c-preprocessor

我粗略地了解了#include对C预处理器的作用,但我完全不理解.现在,我有两个头文件,Move.h和Board.h,它们都是typedef各自的类型(Move和Board).在两个头文件中,我需要引用另一个头文件中定义的类型.

现在我在Board.h中有#include"Move.h",在Move.h中有#include"Board.h".当我编译时,gcc翻转并给我一个很长的(看起来像无限递归)错误信息在Move.h和Board.h之间翻转.

如何包含这些文件,以便我不会无限期地递归包含?

Eva*_*ran 14

你需要研究前向声明,你已经创建了包含无限循环,前向声明是正确的解决方案.

这是一个例子:

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

main.c中

#include "Board.h"
int main() { ... }
Run Code Online (Sandbox Code Playgroud)

注意:每当你创建一个"Board"时,你需要做这样的事情(有几种方法,这里是一个例子):

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 */
Run Code Online (Sandbox Code Playgroud)