Isaac Corbrey
Isaac Corbrey

Reputation: 593

Do you need to explicitly include headers that other headers already include themselves?

Given a header file foo.h:

#include <bar>

// ...

And a file baz.cpp:

#include "foo.h"

// ...

Do you need to explicitly include the bar header into baz.cpp in order to use it? Or can you just start using it since it's included in foo.h?

Upvotes: 1

Views: 78

Answers (2)

Tyler Lewis
Tyler Lewis

Reputation: 881

No, you don't need to. Think of an "#include" as a direction to copy and paste the entire contents of the included file at that line.

other.h:

#include <string>
#include <vector>

std::string getString()
{
    return "A String";
}

main.cpp:

#include <iostream>
#include "other.h"


int main()
{
    std::vector<std::string> vec{getString(), getString()};

    for (auto &it : vec) {
        std::cout << it << std::endl;
    }
    return 0;
}

Upvotes: 2

Sam Varshavchik
Sam Varshavchik

Reputation: 118425

You need to add #include <algorithm> to main.cpp if main.cpp uses any functions or classes, or anything else that's defined in <algorithm>.

What some other translation unit uses is irrelevant.

Upvotes: 2

Related Questions