我大致理解了使用C预处理器所做的#include做什么规则,但我并不完全理解它。现在,我有两个头文件,Move.h和Board.h,这两个文件都是属于它们各自的类型(Move和Board)。在两个头文件中,我需要引用在另一个头文件中定义的类型。
现在,我在Board.h中有#include " Move.h“,在move.h中包含"Board.h”。但是,当我编译时,gcc翻了一下,给了我一个长的(看起来是无限递归的)错误消息,在Move.h和Board.h之间翻转。
如何包含这些文件,使我不会无限期地递归地包含这些文件?
发布于 2010-01-11 21:45:13
您需要查看转发声明,您已经创建了包含的无限循环,前向声明是正确的解决方案。
下面是一个例子:
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!*/
};
#endifBoard.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 */
};
#endifmain.c
#include "Board.h"
int main() { ... }注意:每当创建“委员会”时,您都需要这样做(有几种方法,下面是一个例子):
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 */发布于 2010-01-11 21:50:50
包括警卫将是解决这一问题的一部分。
维基百科的例子:
#ifndef GRANDFATHER_H
#define GRANDFATHER_H
struct foo {
int member;
};
#endif守卫
另一部分,正如其他几个人所指出的,是向前参照。(参考文献)
您可以部分地将其中一个结构声明在另一个之上,如下所示:
#ifndef GRANDFATHER_H
#define GRANDFATHER_H
struct bar;
struct foo {
int member;
};
#endif发布于 2010-01-11 21:50:43
就像这样:
//Board.h
#ifndef BOARD_H
#define BOARD_H
strunct move_t; //forward declaration
typedef struct move_t Move;
//...
#endif //BOARD_H
//Move.h
#ifndef MOVE_H
#define MOVE_H
#include "Move.h"
typedef struct board_t Board;
//...
#endif //MOVE_H通过这种方式可以编译Board.h而不依赖于move.h,并且可以从move.h中包含board.h以使其内容在那里可用。
https://stackoverflow.com/questions/2045159
复制相似问题