1

To further the question from Where to put include statements, header or source?:

If I already have an include statement in the header, eg #include, do I still need to put it inside the source file? I am able to compile with #include in both file, and it's fine when I've dropped #include from source file.

So which is more appropriate, or it doesn't really matters?

Community
  • 1
  • 1

3 Answers3

2

If your 1st include file depends on a 2nd one - for example, the 1st include file references classes or typedefs from the 2nd - put the 2nd include in the 1st include. If they are independent. include both from the source file.

To avoid trouble when a file is included twice, people often put

#ifndef INCLUDE_FILE_NAME_INCLUDED
#define INCLUDE_FILE_NAME_INCLUDED
.......
#endif

at the beginning/end of the included file, so even when you include it twice, INCLUDE_FILE_NAME_INCLUDED will be defined the 2nd time and the file doesn't get evaluated twice.

Guntram Blohm
  • 9,667
  • 2
  • 24
  • 31
  • Thanks for your suggestion. I think most built in stuffs already was guarded. The issue here is more to which is 'correct'. Anyway yeah. Thanks there – Chris Derick Jan 02 '14 at 06:33
1

Short answer: put it only where you must.

If you can compile without the #include directive at all, do that.
Otherwise, if you can compile with it only in the source file, do that.
Otherwise, you must put it in the header, but don't put it in the source file too.

The reason for preferring to put it in the source file rather than the header is so as not to create an unnecessary dependency in other files that #include the header.

Beta
  • 96,650
  • 16
  • 149
  • 150
0

#include cascades. So if you #include <iostream> in file.h, and then #include "file.h" in file.cpp, you will have iostream in file.cpp.

file.h

#include <iostream>
...

file.cpp

#include "file.h"

// iostream definitions are available.

But remember the lesson from the linked question: only #include in a header file when the header itself needs the imported definitions.

Community
  • 1
  • 1
Anthony
  • 12,177
  • 9
  • 69
  • 105