Understanding C++ compilers from a Java / C# perspective

后端 未结 4 1953
有刺的猬
有刺的猬 2021-02-06 14:29

I\'m a moderately experienced Java / C# programmer, and I\'ve recently started learning C++. The problem is, I\'m having trouble understanding how to structure the various heade

4条回答
  •  太阳男子
    2021-02-06 14:43

    This is something that confused me when I first started using C as well. Books don't do a good job of describing the correct use of headers vs. code files.

    The compiler works by loading each .cpp file and compiling it independent of all the others. The first step in compilation is to load all of the headers referred to by #include statements. You can think of it doing a textual insert of the whole foo.h wherever there is a #include "foo.h".

    What are the implications of this for how to structure your files? Header files should have whatever parts of the program are needed for other .cpp files to refer to. As a general rule, implementations should not be in header files. This will cause problems. Header files should include declarations of classes, functions, and global variables (if you must use them).

提交回复
热议问题