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

后端 未结 15 2225
情话喂你
情话喂你 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:06

    There is no better approach, only common and less common cases.

    The more common case is when you have a class/function interface to declare/define. It's better to have only one .cpp/.c with the definitions, and one header for the declarations. Giving them the same name makes easy to understand that they are directly related.

    But that's not a "rule", that's the common way and the most efficient in almost all cases.

    Now in some cases( like template classes or some tiny struct definition ) you'll not need any .c/.cpp file, just the header. We often have some virtual class interface definition in only a header file for example, with only virtual pure functions or trivial functions.

    And in other rare cases (like an hypothetical main.c/.cpp file) if wouldn't be always required to allow code from external compilation unit to call the function of a given compilation unit. The main function is an example (no header/declaration needed), but there are others, mostly when it's code that "connect all the other parts together" and is not called by other parts of the application. That's very rare but in this case a header make no sense.

提交回复
热议问题