Let's say I have 4 source files main, aux1, aux2 and aux3, all of whom work with strings and therefore need to #include <string>
.
The main one will include the 3 aux, since it will use it's functions, but none of the aux needs to include main nor any other aux.
Where should I include string and how could something like #pragma once
help me with this situation?
CodePudding user response:
Headers should include what they use. Deviating from this leads to pain on the long run. Hence:
// aux1.h
#include <string>
// aux2.h
#include <string>
// aux3.h
#include <string>
// main.cpp
#include "aux1.h"
#include "aux2.h"
#include "aux3.h"
You could in principle include <string>
in main
before you include the other headers, then the code will compile even if the other headers do not include <string>
. However, this is very fragile, because then correctness of your code depends on order of includes. The auxX.h
headers should be correct independent of what other headers have already been included or not.
[...] how could something like #pragma once help me with this situation?
You should use header guards for your own headers, though <string>
already has header guards and including it multiple times is a not something you need to worry about.