问题
When file1.c
includes inc.h
(containing the include guard #ifndef INC_H
) for the first time, the #define INC_H
is performed. But now, when another file2.c
includes the same inc.h
, is the macro INC_H
already defined, all it's the same story and previous definition is not propagated here?
回答1:
But now, when another file2.c includes the same inc.h, is the macro INC_H already defined,
Yes and No. It depends.
If
file2.c
includes some header which includesinc.h
, then yes,INC_H
is already defined forfile2.c
. This is true for any level of inclusion.Else, no it is not already defined.
Guards prevent header from being included in a file, indirectly or directly, more than once!
回答2:
The macro definition is not preserved between separate compilations.
回答3:
When you complile file2.c
, the compiler starts afresh. Whatever preprocessor symbols got defined when file1.c
got compiled play no part during the compilation of file2.c
.
回答4:
Definitions are not propagated between *.c
files. If they were, you would not need *.h
files in the first place. (However, you can #include
a *.c
file, but that is another story.)
回答5:
No, think a moment what "#include
" does. It essentially copies the contents of the header file to the place where it is included.
So INC_H
will be defined the first time inc.h
is included in a .c
file. However, this changes nothing for another .c file.
Include guards are useful when include files have other include into it. In these cases you can avoid trouble using the guards.
来源:https://stackoverflow.com/questions/8268687/c-include-guard