Should every C or C++ file have an associated header file?

后端 未结 15 2208
情话喂你
情话喂你 2021-02-04 06:30

Should every .C or .cpp file should have a header (.h) file for it?

Suppose there are following C files :

  1. Main.C

  2. Func1.C

  3. <
15条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-04 07:19

    I used to follow the "it depends" trend until I realized that consistency, uniformity and simplicity are more important than saving the effort to create a file, and that "standards are good even when they are bad".

    What I mean is the following: a .cpp/.h pair of files is pretty much what all "modules" end up anyway. Making the existing of both a requirement saves a lot of confusion and bad engineering.

    For instance, when I see some interface of something in a header file, I know exactly where to search for / place its implementation. Conversely, if I need to expose the interface of something that was previously hidden in .cpp file (e.g. static function becoming global), I know exactly where to put it.

    I've seen too many bad consequences of not following this simple rule. Unnecessary inline functions, breaking any kind of rules about encapsulation, (non)separation of the interface and implementation, misplaced code, to name a few -- all due to the fact that the appropriate sibling header or cpp file was never added.

    So: always define both .h and .c files. Make it a standard, follow it, and safely rely on it. Life is much simpler this way, and simplicity is the most important thing in software.

提交回复
热议问题