What is the difference between a .cpp file and a .h file?

后端 未结 8 2073
余生分开走
余生分开走 2020-12-02 11:52

Because I\'ve made .cpp files then transfered them into .h files, the only difference I can find is that you can\'t #include .cpp files. Is there any difference that I am m

8条回答
  •  一整个雨季
    2020-12-02 12:21

    A header (.h, .hpp, ...) file contains

    • Class definitions ( class X { ... }; )
    • Inline function definitions ( inline int get_cpus() { ... } )
    • Function declarations ( void help(); )
    • Object declarations ( extern int debug_enabled; )

    A source file (.c, .cpp, .cxx) contains

    • Function definitions ( void help() { ... } or void X::f() { ... } )
    • Object definitions ( int debug_enabled = 1; )

    However, the convention that headers are named with a .h suffix and source files are named with a .cpp suffix is not really required. One can always tell a good compiler how to treat some file, irrespective of its file-name suffix ( -x for gcc. Like -x c++ ).

    Source files will contain definitions that must be present only once in the whole program. So if you include a source file somewhere and then link the result of compilation of that file and then the one of the source file itself together, then of course you will get linker errors, because you have those definitions now appear twice: Once in the included source file, and then in the file that included it. That's why you had problems with including the .cpp file.

提交回复
热议问题