Pros & Cons of putting all code in Header files in C++?

前端 未结 17 1872
终归单人心
终归单人心 2020-12-02 15:48

You can structure a C++ program so that (almost) all the code resides in Header files. It essentially looks like a C# or Java program. However, you do need at least one

17条回答
  •  北海茫月
    2020-12-02 15:52

    You misunderstand how the language was intended to be used. .cpp files are really (or should be with the exception of inline and template code) the only modules of executable code you have in your system. .cpp files are compiled into object files that are then linked together. .h files exist solely for forward declaration of the code implemented in .cpp files.

    This results in quicker compile time and smaller executable. It also looks considerably cleaner because you can get a quick overview of your class by looking at its .h declaration.

    As for inline and template code - because both of these are used to generate code by the compiler and not the linker - they must always be available to the compiler per .cpp file. Therefore the only solution is to include it in your .h file.

    However, I have developed a solution where I have my class declaration in a .h file, all template and inline code in a .inl file and all implementation of non template/inline code in my .cpp file. The .inl file is #included at the bottom of my .h file. This keeps things clean and consistent.

提交回复
热议问题