Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Where to add #include <iostream> if my header file are already using std::cout

I have a poor understanding of where to add #include <iostream> in project.


This is LinkedList.h , has a member function decleration print_list()

#include <iostream>

class LinkedList {
public:
    void print_list() const;
};

This is LinkedList.cpp, has the definition of member function.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include "LinkedList.h"

void LinkedList::print_list() const
{
    // code prints something
    std::cout << "There is no element in list\n";
}

This is main.cpp

#include <iostream>
#include <LinkedList.h>

int main()
{
    // code
}

Question is, i do think that(might be wrong) only main.cpp file has to use #include <iostream>.

Can someone explain how to approach this situation and where to add #include <iostream>

>Solution :

Include the header files in every file that directly uses something from the header. It is completely fine to include it multiple times that way. Standard library headers must be able to handle it and any other header should also be designed to support that. (That’s what header guards are used for.)

That way it doesn’t matter how you reorganize includes or your code. Every file always includes what it needs and so you are always safe. Adding includes in files that don’t directly use something from the header becomes unnecessary.

So, in your case, only include <iostream> in LinkedList.cpp which actually uses std::cout. The order of includes is then not really relevant and mostly a style matter.

(This is only a general guideline though that should be mostly fine if you don’t do anything unusual. Because #include is simply just literal inclusion of source code, there are certainly special cases that can occur.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading