应每C或C ++文件中有关联的头文件? [英] Should every C or C++ file have an associated header file?
问题描述
应每.C或.cpp文件应该有一个头(.h)文件呢?
Should every .C or .cpp file should have a header (.h) file for it?
假设有下面的C文件:
-
MAIN.C
Main.C
Func1.C
Func2.C
Func3.C
其中,的main()
是main.c文件。如果有四个标题文件
where main()
is in Main.C file. Should there be four header files
-
Main.h
Main.h
Func1.h
Func2.h
Func3.h
还是应该只有一个头文件的所有.C文件?
Or there should be only one header file for all .C files?
什么是更好的方法?
推荐答案
这是不寻常的有一个 main.h
,因为通常有什么需要被暴露在其他编译单元在编译时。 的main()
本身需要暴露在连接器/启动向上code,但他们不使用头文件。
It's unusual to have a main.h
since there's usually nothing that needs to be exposed to the other compilation units at compile time. main()
itself needs to be exposed for the linker/start-up-code but they don't use header files.
您可以为每个C文件或者一个头文件,或者最有可能为一组相关的C文件的头文件。
You can have either one header file per C file or, most likely, a header file for a related group of C files.
这方面的一个例子是,如果你有一个B树实现,你已经把添加,删除,搜索等在自己的C文件,以尽量减少重新编译的时候code的变化。
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.
这是没有道理在这种情况下要为每个C文件单独的头文件作为标题是API,库到用户的视图。我怀疑用户将要包括6头文件只是为了能够使用的功能。会有有一个 btree.h
文件,并包含所有从内置的B树对象的单个 btree.lib
文件单个C文件。
It doesn't make sense in that case to have separate header files for each C file as the header is the API, the view of the library to the user. I doubt the user would want to include 6 header files just to be able to use the functions. There would be one btree.h
file and a single btree.lib
file containing all of the BTree objects built from the individual C files.
另一个例子是标准的C头文件中找到。我们不知道某些是否有对 stdio.h中
函数多个C文件(这就是我会做,但它不是唯一的方法),但是,即使如果有,他们在API方面视为一个单元。您不必包括 stdio_printf.h
, stdio_fgets.h
等等 - 有一个 stdio.h中
的C运行时库的标准I / O部分。
Another example can be found in the standard C headers. We don't know for certain whether there are multiple C files for 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.
这篇关于应每C或C ++文件中有关联的头文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!