无法转发声明 typedef?

标签 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 结构 tColor tColor;

在 squares.h 中。想法?

最佳答案

I guess it's something like

typedef struct node_square node_square;
typedef struct tColor tColor;

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

这将编译:

node_square* listOfThreatenedSquares(tColor *color);

如果出于某种原因你不想使用指针,你可以包含相应的头文件来为编译器提供类的实际声明。

关于无法转发声明 typedef?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24132030/

相关文章:

c - 为什么通过 typedef-ed 指针访问 struct 的字段不起作用?

c++ - 为什么当一个模板类继承另一个模板类时,需要重新指定typedefs和函数调用限定?

c - 是否可以使用 PMPI 接口(interface)更改 MPI_Probe 的计数?

c - 使用每个选项列表简化编译

c - 当客户端发送超过 10 条消息时,IRC 服务器出现段错误

c - 有没有一种方法可以在结构体内部使用结构体指针而不命名结构体?

更改结构内的调用

c++ - 管道以提供文件作为 C 程序的输入

c - 如何将月份(int)转换为月份名称(字符串)

c - 在 typedef 结构中填充 int 数组时出错