【问题标题】:Cannot forward declare a typedef?无法转发声明 typedef?
【发布时间】:2014-06-10 02:41:52
【问题描述】:

我正在通过编写国际象棋应用程序来学习 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 中。想法?

【问题讨论】:

    标签: c struct typedef forward-declaration


    【解决方案1】:

    我猜是这样的

    typedef struct node_square node_square;
    typedef struct tColor tColor;
    

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

    这将编译:

    node_square* listOfThreatenedSquares(tColor *color);
    

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

    【讨论】:

    • 它不起作用的原因是我没有使用与原始头文件中相同的声明。需要非常细致的东西。 Danke schön。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多