Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reincluding header in implementation

Tags:

c++

header

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.

like image 739
Ruggero Turra Avatar asked Dec 11 '10 12:12

Ruggero Turra


People also ask

Do header files have implementation?

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.

What is the need of including header files in a program?

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.

What is the main purpose of a header?

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.


1 Answers

The practice I follow:

  • foo.h should directly include all headers its source code needs (i.e. #include <string> if there is std::string in foo.h)
  • foo.cpp should directly include foo.h plus all other headers its own source code needs, except for those already directly included by 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.

like image 151
pts Avatar answered Oct 02 '22 04:10

pts