Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I include header files, in the .cpp or in the .h file? [duplicate]

Tags:

c++

Where should I include header files, in the .cpp or in the .h file?

I am working on a project now and trying to come up with a clean way to follow once and for all. The state now is, files are included in both .cpp and .h files. For example, sometimes they have #include in someFile.h and sometimes in someFile.cpp.

I wonder, does it matter where you do the include? It works both ways, but are there any pitfalls?

Thanks

like image 350
user2381422 Avatar asked May 29 '13 18:05

user2381422


People also ask

Where should I include header files?

In C language, header files contain the set of predefined standard library functions. You request to use a header file in your program by including it with the C preprocessing directive “#include”. All the header file have a '. h' an extension.

Should I #include in headers or CPP?

To minimize the potential for errors, C++ has adopted the convention of using header files to contain declarations. You make the declarations in a header file, then use the #include directive in every . cpp file or other header file that requires that declaration.

Should a CPP file include its own header?

Headers include everything they need to compile.Including the header first is simply a way of ensuring this contract is met. Because there is nothing included before the first include in the source file, the inclusion guarantees that the header will compile independently of other headers.

Should you include header files in header files?

A TL;DR definition: A header file must include the header files that directly define each of the types directly used in or that directly declare each of the functions used in the header file in question, but must not include anything else.


2 Answers

In general, you should only include headers in .h files that are needed by those headers. In other words, if types are used in a header and declared elsewhere, those headers should be included. Otherwise, always include headers only in .cpp or .c files. This keeps compilation time to a minimum and better shows what files are needed.

An exception is to include very commonly used headers in one standardized .h file, often called Stdafx.h, and then enable pre-compiled headers.

like image 173
shipr Avatar answered Oct 24 '22 05:10

shipr


Include whatever header that is required by the code in the current file. No matter whether it is a .h or .cpp file

like image 35
GuLearn Avatar answered Oct 24 '22 05:10

GuLearn