为什么C/C++的预处理指令#include不自动让所包含的文件只包含一次?
大家讲道理
大家讲道理 2017-04-17 11:15:45
0
4
961

在C/C++中#include所包含的头文件里面必须显式声明

#ifndef __HEADER_H_DEFINE__
#define __HEADER_H_DEFINE__

#endif

或者有些编译器支持

#pragma once

编译器完全有能力在执行预处理指令#include时使同一个文件只包含一次,但是却没有这么做,为什么?是否有需要包含同一个文件超过一次的情况?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(4)
黄舟

1. C/C++ functions and variables can be declared repeatedly. Conditional judgment is to prevent unnecessary functions from being declared, causing conflicts.

It is to avoid repeated compilation, not to solve repeated declarations.

2. #pragma once The same file will not be compiled multiple times. Note that the same file mentioned here refers to one physical file, not two files with the same content.

C/C++ does not have the requirement that each class corresponds to one file like Java, so even if #pragma once is used, conditional judgments should be added to the header file.

刘奇

#include can include not only h files, but also other types of files.
It is indeed possible to generate an executable file that contains the same header file multiple times. Let me give you a poor example:

foo.h:

a = 43;

foo.c:

static int foo(void)
{
    int a;
#include "foo.h"
    return a;
}

int main(void)
{
    int a;
    int b;

#include "foo.h"
    b = foo();
    printf("a is %d, b is %d\n", a, b);
    return 0;
}

If the preprocessor automatically includes the header file only once, then variable a will not be initialized.
In actual projects, you can still see that some very large data is placed in a file, and then #include the file's value assigned to a variable.
There are also examples of including a c file, such as redis.

洪涛

Another function is that sometimes a header file will be included by other header files, such as
types.h is included by header_a.h and header_b.h. When a C file contains both header_a.h and header_b.h, if there is no #ifdef/#define/#endif, then types.h will be included twice. , so that statements such as typedef unsigned int uint32_t; in types.h will appear twice in the same c file, and the compiler will expose warnings or errors such as redefinition of typedef 'foobar'.

巴扎黑

Many projects need to include the same header file multiple times. It turns out that I have seen the header file of flascc. A certain header file is included by another no less than five times. Generally, the macro definition is modified in B to include A, and the macro definition is modified again to include A again.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template