2

Say I have a file, player.h, and in player.h I have included the following:

#include <iostream>
#include <string>
#include <vector>
#include <fstream>

Would I need to include these again in player.cpp, where I flesh out the functions declared in the header file? If I don't, do I need to include them when I run main.cpp, which calls the functions from my various .cpp's and .h's

School never really told me whether or not to do it, so I've always included everything across the board. If it's unnecessary is there any noticeable difference between including everything multiple times and not doing so?

Skullruss
  • 63
  • 8
  • No, you don't need to include them in `player.cpp` if `player.cpp` `#include`s `player.h` - but it's often recommended to include what you use in every file. – Ted Lyngmo Aug 05 '21 at 15:08
  • Not *entirely* sure what you mean but, if you `#include "player.h"` in your player.cpp file, then those `#include` lines will be automatically added to player.cpp. Is that what you're asking? – Adrian Mole Aug 05 '21 at 15:08
  • @Ted But doesn't including lots of system headers *repeatedly* sort of defy the purpose of a single, pre-compiled header file that already includes them? – Adrian Mole Aug 05 '21 at 15:10
  • @AdrianMole Yes, I guess that's true too. – Ted Lyngmo Aug 05 '21 at 15:17

1 Answers1

3

An include preprocessor directive tells the preprocessor to replace it with the contents of the file. Hence when you have

// some_header.h
#include <foo>

and

// some_source.cpp
#include <some_header.h>

then if you compile source.cpp, what the compiler gets to see after the preprocessing step is this:

// some_source.cpp
... contents of foo ...

That is: The #include <some_header.h> is replaced by contents of that header and #include <foo> is replaced by contents of foo.

No, you do not need to include headers twice. Though as headers should have include guards it also won't hurt. The recommonendation is: Include what you use (but not more).

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • Thank you, very much, I appreciate the clarity of the answer. I figured that including twice was not necessary, but I figured checking was worth it. It's interesting that including more than once doesn't hurt a project, though. My thought process was that it could slow down the project if it loaded the same library 100 times, for example. – Skullruss Aug 05 '21 at 15:26
  • @Skullruss here you can find more about the preprocessor and include guards: https://stackoverflow.com/a/8020211/4117728 – 463035818_is_not_an_ai Aug 05 '21 at 15:30