What should go into an .h file?

2019-01-01 00:48发布

When dividing your code up into multiple files just what exactly should go into an .h file and what should go into a .cpp file?

12条回答
人间绝色
2楼-- · 2019-01-01 01:01

What compiles into nothing (zero binary footprint) goes into header file.

Variables do not compile into nothing, but type declarations do (coz they only describe how variables behave).

functions do not, but inline functions do (or macros), because they produce code only where called.

templates are not code, they are only a recipe for creating code. so they also go in h files.

查看更多
只靠听说
3楼-- · 2019-01-01 01:03

Header files (.h) are designed to provide the information that will be needed in multiple files. Things like class declarations, function prototypes, and enumerations typically go in header files. In a word, "definitions".

Code files (.cpp) are designed to provide the implementation information that only needs to be known in one file. In general, function bodies, and internal variables that should/will never be accessed by other modules, are what belong in .cpp files. In a word, "implementations".

The simplest question to ask yourself to determine what belongs where is "if I change this, will I have to change code in other files to make things compile again?" If the answer is "yes" it probably belongs in the header file; if the answer is "no" it probably belongs in the code file.

查看更多
浅入江南
4楼-- · 2019-01-01 01:10

the header file (.h) should be for declarations of classes, structs and its methods, prototypes, etc. The implementation of those objects are made in cpp.

in .h

    class Foo {
    int j;

    Foo();
    Foo(int)
    void DoSomething();
}
查看更多
查无此人
5楼-- · 2019-01-01 01:13

Your class and function declarations plus the documentation, and the definitions for inline functions/methods (although some prefer to put them in separate .inl files).

查看更多
一个人的天荒地老
6楼-- · 2019-01-01 01:14

In general, you put declarations in the header file and definitions in the implementation (.cpp) file. The exception to this is templates, where the definition must also go in the header.

This question and ones similar to it has been asked frequently on SO - see Why have header files and .cpp files in C++? and C++ Header Files, Code Separation for example.

查看更多
看淡一切
7楼-- · 2019-01-01 01:15

in addition to all other answers, i will tell you what you DON'T place in a header file:
using declaration (the most common being using namespace std;) should not appear in a header file because they pollute the namespace of the source file in which it is included.

查看更多
登录 后发表回答