i have a question where i should place #includes in a file?


Here is what i tend to have
example.h
#include <iostream>
#include <string>

example.cpp
#include <iostream>
#include "example.h"

------------------------------------------------

Is This what i want?
example.h
#include <iostream>
#include <string>

example.cpp
#include "example.h"


What should i strive to achieve?
1.) Place all included possible in the .h file needed to compile without error...if wont compile because .cpp is missing includes then place needed includes to compile in .cpp file?

Including libraries in your header file is safe, but might get slow if multiple other files include that header file. Try to think where in your code you need what service from what library.

Best practice is to include the exact header you need in each file it's needed. For example:

#ifndef EXAMPLE_H
#define EXAMPLE_H

// example.h
#include <string>

std::string foo();

#endif
// example.cpp
#include <string>
#include "example.h"

std::string foo()
{
   // ...
}
// main.cpp
#include <iostream>
#include <string>
#include "example.h"

int main()
{
    std::string s = foo();

    std::cout<< s <<'\n;
}

Note how <string> is included explicitly in each file. This is because std::string is used directly in each file. You could legally leave the inclusion out in main.cpp and example.cpp because example.h already includes it, but that's not best practice because now anyone reading either main.cpp or example.cpp won't know immediately that you're using the std::string class without reading through the code and then diving into the headers to make sure you're including <string> somewhere.

Inclusion guards ensure that regardless of how many times you include a header, it's only really included once for each translation unit. The standard headers also follow this design and are properly idempotent. So don't worry about multiple inclusions causing errors.

This article has been dead for over six months. Start a new discussion instead.