Alex
Alex

Reputation: 51

Including a library in both the header file and the cpp file

I am new to C++. I have seen code that includes a library file (string as an example) in both the header and cpp file. Will this cause duplicate code if #ifndef is not used? or is the preprocessor smart enough to ignore it. Is it normal to include the same library in both files?

test.h

#include <string>
.
.
.

test.cpp

#include <string>
#include "test.h"
.
.
.

Upvotes: 5

Views: 2239

Answers (2)

eerorika
eerorika

Reputation: 238461

Is it normal to include the same library in both files?

Yes. It is normal to include a header into multiple files.

Whenever you use a declaration from a header, you should include that header. If you use std::string in test.h, then you should include <string> in test.h. If you use std::string in test.cpp, then you should in include <string> in test.cpp. Whether <string> happens to be included in one of the headers included by test.cpp is irrelevant and is something that shouldn't be relied upon.

Will this cause duplicate code if #ifndef is not used?

If a header doesn't have a header guard, then including it multiple times will indeed cause its content to be duplicated, yes.

or is the preprocessor smart enough to ignore it.

The preprocessor doesn't ignore any includes. Each include will be processed. A preprocessor may be smart enough to optimise inclusion of a header that it knows would be empty due to an include guard.

Upvotes: 3

Kon
Kon

Reputation: 4099

All C++ standard library header files have ifndef guards. It is safe to include them in multiple files.

The rule of thumb is to include the file everywhere where its definitions are needed. This means if you're using std::string in both h and cpp files, include <string> in both.

For any of your own header files, you should always use ifndef guards for the same purpose.

Upvotes: 2

Related Questions