Reputation: 25590
Question about header files in C++: when I should use them. If I write small program should I create header file or can I just declare my classes in .cpp files? What is a good practice? If you give links to articles about it, it would be good. I could not find good ones.
Upvotes: 0
Views: 126
Reputation: 755064
Use header files when you need to share information between several source files. The header file, used carefully, will ensure consistency between a file defining some functionality and other files using that functionality.
When a program consists of a single (source) file, there is no need to create a header. When a program needs more than one source file (say two source files), there must be at least one function or variable 'shared' between the two files (because if there wasn't, one of the files would be redundant). You should have a header to describe the shared function or variables so that the producer and consumer agree on the common functionality.
The corollary is that a header should not describe anything not needed by the consumers of the functionality. Just because the implementation needs to use some second header, the consumer should not be made to include it. If the second header provides definitions used in the interface, then it should indeed be included in the common header.
OK - lots of verbiage. A concrete example:
extern int somefunc(int, int);
#include "source1.h"
int somefunc(int a, int b)
{
return a + b;
}
#include <iostream>
#include "source1.h"
using namespace std;
int main()
{
int x = somefunc(1, 3);
cout << "somefunc(1, 3) is " << x << endl;
}
The header here is necessary to provide the assurance that everything is consistent. Both source1.cpp
and program.cpp
must include the header to ensure the consistency.
Note that if somefunc()
was defined in program.cpp
there would be no point in providing the header.
Now suppose we modify somefunc()
:
#include "source1.h"
#include <iostream>
using namespace std;
int somefunc(int a, int b)
{
cout << "a = " << a << ", b = " << b << endl;
int x = a + b;
cout << "x = " << x << endl;
return x;
}
Superficially, you could revise source1.h
so it includes <iostream>
, but that would be a bad move. The interface of the function defined, somefunc()
, does not depend on <iostream>
, so the header should not include <iostream>
.
Upvotes: 2
Reputation: 53
Another reason why you should use header files when you distributing your binaries. You provide the header file and the dll file to your clients.
Upvotes: 1
Reputation: 29985
Header files are always a good idea but strictly speaking you don't need them. Especially when using multiple .cpp files it's strongly recommended to use them.
The rule I used before "always use them" was: any cpp that has its functions accessible from other cpp files should use a header file to "export" the functions.
Best practice: always use header files.
Upvotes: 2