suppose I have a header foo.h
like this:
#ifndef FOO_H
#define FOO_H
#include <string>
#include "non_standard_class.h"
std::string foo(MyClass a);
...
#endif
and the implementation foo.cpp
will be
#include <vector>
#include "foo.h"
std::string foo(MyClass a)
{
std::vector<int> x;
MyClass b;
...
}
is it a good pratice to re-include <string>
and non_standard_class.h
in foo.cpp
? The point is: if I read foo.cpp
how can I understand where does MyClass come from? I need to look at foo.h
but it will be more difficult.
In C, you cannot have the function definition/implementation inside the header file. However, in C++ you can have a full method implementation inside the header file.
Header files serve two purposes. System header files declare the interfaces to parts of the operating system. You include them in your program to supply the definitions and declarations you need to invoke system calls and libraries.
A header is the top margin of each page, and a footer is the bottom margin of each page. Headers and footers are useful for including material that you want to appear on every page of a document such as your name, the title of the document, or page numbers.
The practice I follow:
#include <string>
if there is std::string
in foo.h)Another formulation of this practice: in foo.*, include only those headers the source code needs. If a header is needed by only foo.cpp (but not by foo.h), then include it from foo.cpp, otherwise include it from foo.h.
So, in your case, I wouldn't #include <string>
in foo.cpp, because it's already included by foo.h.
Let's assume that string
does an #include <vector>
, and foo.h contains std::vector
. In this case, I'd #include <vector>
in foo.h, because its source code needs it – and it doesn't matter that string
already includes it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With