C头文件循环 [英] C header file loops

查看:96
本文介绍了C头文件循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一对夫妇的头文件,它归结为:

I have a couple of header files, which boil down to:

tree.h:
#include "element.h"

typedef struct tree_
{
    struct *tree_ first_child;
    struct *tree_ next_sibling;
    int tag;
    element *obj;
    ....
} tree;

element.h:
#include "tree.h"

typedef struct element_
{
    tree *tree_parent;
    char *name;
    ...
} element;

我的问题是,它们都相互引用,因此包括树的需求元素,元素需要包括树。

The problem I have is, that they both reference each other, so tree needs element included, and element needs tree included.

这是不行的,要初始化树结构,要素结构必须是已知的事情,但初始化元​​素结构,树形结构必须是已知的。

This doesn't work, to initialise the 'tree' structure, the element structure must be known about, but to initialise the element structure, the tree structure must be known about.

你如何解决这些类型的循环(我认为它有一些事情与'向前声明'?)?

How do you resolve these types of loops (I think it has some thing to do with 'forward declaration'?)?

推荐答案

我觉得这里的问题不是缺少后卫包括但事实上,这两个结构需要彼此在他们的定义。所以这是一个类型定义翰和蛋的问题。

I think the problem here is not the missing include guard but the fact that the two structures need each other in their definition. So it's a type define hann and egg problem.

要解决这些在C或C ++的方法是做前向声明的类型。如果你告诉编译器元素是某种形式的结构,编译器能够产生一个指针。

The way to solve these in C or C++ is to do forward declarations on the type. If you tell the compiler that element is a structure of some sort, the compiler is able to generate a pointer to it.

例如

在tree.h中:

// tell the compiler that element is a structure typedef:
typedef struct element_ element;

typedef struct tree_ tree;
struct tree_
{
    tree *first_child;
    tree *next_sibling;
    int tag;

    // now you can declare pointers to the structure.
    element *obj;
};

这样,你不必包括内部tree.h中element.h展开了。

That way you don't have to include element.h inside tree.h anymore.

您也应该包括的得分后卫在你的报头的文件。

You should also put include-guards around your header-files as well.

这篇关于C头文件循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆