首页 > 解决方案 > C中相互依赖的结构

问题描述

我正在关注 Ruslan Spivak 的文章系列/教程“让我们构建一个简单的解释器”,这是在 Python 中构建一个简单的 Pascal 解释器的指南。我正在尝试在 C 中跟进。我对添加抽象语法树的部分感到困惑。

我有这个头文件:

#include "tokens.h"
struct binopnode
{
    struct node left;
    token op;
    struct node right;
};

struct node
{
    union nvalue value;
    enum ntype type;
};

enum ntype
{
    NUM,
    BINOP,
};

union nvalue
{
    struct binopnode binop;
    struct numnode num;
};

struct numnode
{
    token tok;
};

其中"tokens.h"包括token typedef'd 结构。

我的问题是我的编译器:

Apple clang version 12.0.5 (clang-1205.0.22.9)
Target: x86_64-apple-darwin20.3.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

抛出Incomplete Type错误。

从这些链接:
http ://c-faq.com/decl/mutrefstructs.html
C 中的循环定义
我猜我必须使用指针,但我完全不知道在哪里。

标签: cstructenumsunionsforward-declaration

解决方案


您可以先声明结构,然后再将它们作为指针引用。

在 C 中,当一个结构 A 包含另一个结构 B 时,A 将需要 B 大小的内存区域。如果结构 A 包含结构 B 而结构 B 包含结构 A,编译器无法决定应该为每个结构分配多少内存。因此,如果您想使用相互引用的结构,您应该至少使用其中一个作为指针。

#include "tokens.h"

struct binopnode;
struct node;
enum ntype;
union nvalue;
struct numnode;

struct binopnode
{
    struct node *left;
    token op;
    struct node *right;
};

struct node
{
    union nvalue *value;
    enum ntype type;
};

enum ntype
{
    NUM,
    BINOP,
};

union nvalue
{
    struct binopnode *binop;
    struct numnode *num;
};

struct numnode
{
    token tok;
};

推荐阅读