我正在通过编写国际象棋应用程序来学习 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 结构 tColor tColor;
在 squares.h 中。想法?
最佳答案
I guess it's something like
typedef struct node_square node_square; typedef struct tColor tColor;
这是对的 - 这确实是一种前向声明 node_square
和 tColor
的方法。但是,前向声明类型被认为是不完整,因此在使用它们时需要遵循一条规则:不能声明前向声明类型本身的变量、数组、结构成员或函数参数;仅允许使用指针(或指向指针的指针、指向指针的指针等)。
这将编译:
node_square* listOfThreatenedSquares(tColor *color);
如果出于某种原因你不想使用指针,你可以包含相应的头文件来为编译器提供类的实际声明。
关于无法转发声明 typedef?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24132030/