Skullruss
Skullruss

Reputation: 83

Do I need to include libraries in my main cpp, even if it's been included in a header file?

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?

Upvotes: 3

Views: 3128

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122133

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).

Upvotes: 4

Related Questions