简体   繁体   English

在C中包含头文件

[英]include header files in C

I am a newbie to C and C++ language, I have a question about header files in C: 我是C和C ++语言的新手,我对C中的头文件有疑问:

ah

#define HELLO (1)
typedef struct
{
   int a;
   int b;
} hello;

bh BH

#include "a.h"
#define NUMBER (3)

main.c main.c中

#include "b.h"

in main.c , does struct and macro defined in ah can be used in main.c ? main.c ,可以在main.c使用ah定义的structmacro吗?

Sure you can use both Struct and MACROS in the main.c 确保可以在main.c中同时使用Struct和MACROS

You need to be aware of the C Compilation Process, Before main.c is being compiled or linked, there is the pre-processor step: 您需要了解C编译过程,在对main.c进行编译或链接之前,需要执行预处理器步骤:

Preprocessor : 预处理器

  • The input to this phase is the .c File and .h Files 此阶段的输入是.c文件和.h文件
  • The preprocess process the preprocessor keywords like #define, #ifdef, #include, etc. and generate a new .pre file or .i file after the text replacement process. 预处理过程对预处理程序关键字(如#define,#ifdef,#include等)进行处理,并在文本替换过程之后生成一个新的.pre文件或.i文件。
  • The output of this phase is a C Code without any preprocessor keyword. 该阶段的输出是没有任何预处理关键字的C代码。

在此处输入图片说明

So the main.c will actually look like this: 所以main.c实际上看起来像这样:

#define HELLO (1)
typedef struct
{
   int a;
   int b;
} hello;
#define NUMBER (3)

And then replace all macros, here you don't use HELLO or NUMBER, so the pure c main file will be: 然后替换所有宏,这里您不使用HELLO或NUMBER,因此纯c主文件将是:

typedef struct
{
   int a;
   int b;
} hello;

Yes, it can be used. 是的,可以使用。 That is the sole purpose of #include ing of header files. 这是#include头文件的唯一目的。

For more information, you can see the preprocessed version of code. 有关更多信息,您可以查看代码的预处理版本。 Use 采用

gcc -E <filename.c>  //main.c, in this case

There you can see the presence of the struct and MACROS definde in the included header files. 在那里,您可以在随附的头文件中看到struct和MACROS定义的存在。

Yes, #include directives themselves appearing in included files have their normal effect, up to an implementation-defined limit on the number of levels of inclusion. 是的,出现在包含文件中的#include指令本身具有正常的作用,直到实现定义的包含级别数限制。 The "normal effect" is equivalent to textual interpolation -- that is, there is no separate scoping for the contents of included files -- so any declaration appearing in any directly or indirectly included file is visible to all code following the point of inclusion. “正常效果”等效于文本插值-也就是说,对于包含文件的内容没有单独的作用域确定-因此,出现在任何直接或间接包含文件中的任何声明对于包含点之后的所有代码都是可见的。

Yep, #include statements can chain multiple files together. 是的,#include语句可以将多个文件链接在一起。 #include literally copies and pastes the contents of one file into another, so you can think of it as a one-after-another effect. #include实际上将一个文件的内容复制并粘贴到另一个文件中,因此您可以将其视为一个接一个的效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM