Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 标准库包含多个文件多次?_C_Compiler Construction_C Preprocessor_Stdio_Kernighan And Ritchie - Fatal编程技术网

C 标准库包含多个文件多次?

C 标准库包含多个文件多次?,c,compiler-construction,c-preprocessor,stdio,kernighan-and-ritchie,C,Compiler Construction,C Preprocessor,Stdio,Kernighan And Ritchie,在K&R书籍(第59页)(编辑:第二版,涵盖ANSIC)中,建议更容易将较大的项目拆分为多个文件。在每个文件中,顶部通常包含几个库:例如getop.c需要stdio.h,stack.c和main.c也需要stdio.h 代码片段如下所示: //main.c #include <stdio.h> #include <stdlib.h> #include "calc.h" int main(void) { //etc } //getop.c #include &l

在K&R书籍(第59页)(编辑:第二版,涵盖ANSIC)中,建议更容易将较大的项目拆分为多个文件。在每个文件中,顶部通常包含几个库:例如getop.c需要stdio.h,stack.c和main.c也需要stdio.h

代码片段如下所示:

//main.c
#include <stdio.h>
#include <stdlib.h>
#include "calc.h"
int main(void)
{
    //etc
}


//getop.c
#include <stdio.h>
#include <ctype.h>
#include "calc.h"
getop()
{
    /*code*/
}

//stack.c
#include <stdio.h>
#include "calc.h"
void push(double val)
{
    //code
}
文件“mod2.h”

文件“prog.c”


因为他们使用了一种叫做包含保护的东西,假设您自己的包含文件要在其中包含多次,那么您就可以这样做了

MyHeader.h

#ifndef MY_HEADER_H
#define MY_HEADER_H
/* file content goes here */
#endif /* MY_HEADER_H */
然后你有另一个标题

**AnotherHeader.h**

#ifndef MY_ANOTHER_HEADER_H
#define MY_ANOTHER_HEADER_H
#include "MyHeader.h"
/* file content goes here */
#endif /* MY_ANOTHER_HEADER_H */
在你的节目里

main.c

/* 
 * MY_HEADER_H is undefined so it will be defined and MyHeader.h contents 
 * will be included.
 */
#include "MyHeader.h" 
/*
 * MY_HEADER_H is defined now, so MyHeader.h contents will not be included
 */
#include "AnotherHeader.h"

int main()
{
    return 0;
}
由于每个编译单元只包含一次包含的文件,因此生成的二进制大小不会增加,此外,头文件的包含只会在这些头文件中声明字符串文字时增加编译文件的大小,否则,它们只向编译器提供有关如何调用给定函数的信息,即如何向其传递参数以及如何存储其返回值

我想我真正想问的是,编译器如何解决一个库在一个项目中被多次包含的问题


通过
#include
,您不包括库,您只包括它的声明,因此编译器知道存在哪些函数。链接器负责包括一个库并将所有内容放在一起。

您可能需要阅读和了解。
\uuuu MY\u HEADER\u H\uuu>是一个保留名称
#ifndef MY_HEADER_H
#define MY_HEADER_H
/* file content goes here */
#endif /* MY_HEADER_H */
**AnotherHeader.h**

#ifndef MY_ANOTHER_HEADER_H
#define MY_ANOTHER_HEADER_H
#include "MyHeader.h"
/* file content goes here */
#endif /* MY_ANOTHER_HEADER_H */
/* 
 * MY_HEADER_H is undefined so it will be defined and MyHeader.h contents 
 * will be included.
 */
#include "MyHeader.h" 
/*
 * MY_HEADER_H is defined now, so MyHeader.h contents will not be included
 */
#include "AnotherHeader.h"

int main()
{
    return 0;
}