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

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

问题描述

我在工作区中有一个带有 *.c 和 *.h 文件的纯 C 代码.
我有一个头文件 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;

但是当我尝试在另一个头文件 2.h 中声明一个 struct my1 类型的变量时,如下所示:-

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?

出于某种安全原因,无法发布实际的代码片段,如果问题在某种程度上造成一些可读性问题,我们深表歉意.

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 中的 typedef(而不是 C++)

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.

你可以这么想,就好像你把代码粘贴到文件里一样.它包含在那个时候.

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

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

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