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

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

    For a start, it would be unusual to have a main.h since there's usually nothing that needs to be exposed to the other compilation units at compile time. The main() function itself needs to be exposed for the linker or start-up code but they don't use header files.

    You can have either one header file per C file or, more likely in my opinion, a header file for a related group of C files.

    One example of that is if you have a BTree implementation and you've put add, delete, search and so on in their own C files to minimise recompilation when the code changes.

    It doesn't really make sense in that case to have separate header files for each C file, as the header is the API. In other words, it's the view of the library as seen by the user. People who use your code generally care very little about how you've structured your source code, they just want to be able to write as little code as possible to use it.

    Forcing them to include multiple distinct header files just so they can create, insert into, delete from, and search, a tree, is likely to have them questioning your sanity :-)

    You would be better off with one btree.h file and a single btree.lib file containing all of the BTree object files that were built from the individual C files.


    Another example can be found in the standard C headers.

    We don't know for certain whether there are multiple C files for all the stdio.h functions (that's how I'd do it but it's not the only way) but, even if there were, they're treated as a unit in terms of the API.

    You don't have to include stdio_printf.h, stdio_fgets.h and so on - there's a single stdio.h for the standard I/O part of the C runtime library.

提交回复
热议问题