无法转发声明typedef?

时间:2014-06-10 02:41:52

标签: c struct typedef forward-declaration

我正在通过编写国际象棋应用程序来学习C,我对循环引用有疑问。我的linkedList.h看起来像这样:

#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#ifdef  __cplusplus
extern "C" {
#endif
#ifdef  __cplusplus
}
#endif
#endif  /* LINKEDLIST_H */

#include <stdlib.h>
#include "squares.h"

typedef struct node {
tSquare c;
struct node * next;
} node_square;



void createEmptyList(node_square* n);
int isEmptyList(node_square* n);
int insertAtBeginning(node_square** n, tSquare c); 
void print_list(node_square * head);

在我的squares.h中,我希望包含linkedList.h功能,以便我可以返回受其中一方(黑色或白色)威胁的链接列表:

#ifndef SQUARES_H
#define SQUARES_H
#ifdef  __cplusplus
extern "C" {
#endif
#ifdef  __cplusplus
}
#endif
#endif  /* SQUARES_H */

typedef struct {
    int file;
    int rank;
} tSquare;

node_square* listOfThreatenedSquares(tColor color); <--- undefined types in compilation time

我读过我应该使用的是前向参考;我试图使用它,以便在squares.h文件中我可以使用类型node_square和tColor(在另一个名为pieces.h的文件中定义),但无论我如何声明类型,它都无法正常工作。我想这就像是

typedef struct node_square node_square; typedef struct tColor tColor;

在squares.h中。想法?

1 个答案:

答案 0 :(得分:4)

  

我想这就像是

typedef struct node_square node_square;
typedef struct tColor tColor;

这是对的 - 这确实是向前声明node_squaretColor的一种方式。但是,前向声明的类型被认为是不完整,因此在使用它们时需要遵循一个规则:您不能声明前向声明类型本身的变量,数组,结构成员或函数参数;只允许指针(或指向指针的指针,指向指针的指针等)。

这将编译:

node_square* listOfThreatenedSquares(tColor *color);

如果由于某种原因不希望使用指针,可以包含相应的标题,以便为编译器提供类的实际声明。

相关问题