如何包容头文件的发生呢? [英] How does inclusion of header file happen?

查看:108
本文介绍了如何包容头文件的发生呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个普通的C code。与* .c和*工作区中的.h文件。

我有一个头文件1.H声明一些结构

I have a plain C code with *.c and *.h files in the workspace.
I have a header file 1.h declaring some structure as

struct my1
{ 
int a;
..
..
}my_t;

但是,当我尝试声明类型结构MY1的变量在另一头文件2.H如下: -

But when i try to declare a variable of type struct my1 in another header file 2.h as follows:-

struct my1 variable1;

据在此声明一点给人错误。

It gives error at this declaration point.

看起来MY1这里未定义在2.H文件。

Looks like my1 is undefined here in 2.h file.

在文件1.H我需要包括2.H,所以在文件2.H我不能包括1.H,怕递归列入。

In file 1.h I need to include 2.h, so in file 2.h I cannot include 1.h, for fear of recursive inclusion.

我的问题是: -


  1. 我需要做什么声明来解决编译错误,在这种情况下?

  1. What do i need to declare to resolve the compilation error in this case?

这整个事情让我想起大约头文件包含进一步的问题。

This whole thing made me think about further questions about header file inclusions.

是如何包含头文件,以什么顺序,这头文件先那么哪个?

How are the header files included, in what order, which header file first then which one?

将列入递归头文件会导致错误一个文件在内的其他和其他包括第一?

Will recursive inclusion of header files cause errors one file including other and other including first?

无法张贴实际code片段的一些安全原因,很抱歉,如果这个问题有点带来了一些可读性的问题。

Could not post the actual code snippets for some security reason, so sorry if the question somewhat poses some readability problems.

推荐答案

您应该把一个包含锁所有的.h文件开始(这被称为的包括后卫):

You should start by putting an inclusion lock in all your .h files (this is called an include guard):

#ifndef ONE_H
#define ONE_H

//rest of header

#endif //ONE_H

这样,你可以将其包含多次。

That way you can include it multiple times.

二:

typedef struct my1 { int a; .. .. }my_t;

您需要C(不是C ++)的typedef

You need a typedef in C (not in C++)

标头包括在包容的顺序

如果您编译它与开头的文件abc.c:

If you compile a file abc.c which starts with:

#include "a.h"
#include "b.h"

然后A.H将被首次列入,那么b.h。

then a.h will be included first, then b.h.

您能想到的它,如果粘贴在文件中的code。它被包含在该点

You could think of it, as if you paste the code in the file. It is included at that point.

这篇关于如何包容头文件的发生呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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