Why including same headers in multiple cpp files and then their compilation works? [duplicate]

我与影子孤独终老i 提交于 2019-12-01 14:10:48

The preprocessor simply reads the header files and puts them into the translation units where the #include directive is. If one header file is included in one source file, only that file knows about the declarations in that header file.

You also should know the difference between declarations and definitions. When you declare something, you just tells the compiler that "this thing exists and is of type this-and-that". When you define something, you tell the compiler "this is the thing I declared before".

You can have multiple declarations of the same thing. because they only act as meta-data for the compiler, and are not used outside its translation unit. You can however only have one definition of something. That's why you can't define global variables/functions in header files included in multiple source files.

Also, In this answer I talk about "source files", "header files" and "translation units". Header files are the files you #include. Source files is the files that does the including (so to speak). And a translation unit is the complete preprocessed source, complete with the source and all included header files, and which is passed on to the actual compiler.

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