C include guard [duplicate]

非 Y 不嫁゛ 提交于 2019-12-23 19:07:50

问题


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 includes inc.h, then yes, INC_H is already defined for file2.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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!