Search code examples
c++header-files

Should I put external header in .h file or .cpp file?


Let say I have a function defined in foo.h:

#pragma once 
#include <vector>
#include <string>
void foo(std::vector<std:string> input);

and In in the implementation file foo.cpp I need to use another library (say std::map) for implementing the function foo.

void foo(std::vector<std:string> input){
...
std::map ...
...
}

Note that std:map is not needed in the declaration and it is only implementation specific.

Should I put #include <map> in the foo.h or foo.cpp file?

I know the code will compile for both cases, I am wondering what is a good practice?


Solution

  • Put the include in the source file where it is needed.

    Putting it in the header would needlessly cause all users of the header to also include <map> regardless of whether they need it or not.

    For trivial projects this is irrelevant, but for large projects it matters since pointless includes increase compilation time and increase the risk of name collisions.