gotMoreGoodstuff gotMoreGoodstuff - 10 months ago 34
C++ Question

No header files included in file but can still use classes/functions from unincluded header files

Here's some the code from the file in question, called Global.h, which is used in other header files and seems to compile just file:

#pragma once

enum SType {null, lab, assignment, testPrep};
enum Code {none, 123, 222, 333, 432};

template<typename D>
bool validate(D task = string, D date = string) {

bool result = true;

if (task.size() < 3) {
cout << "Task too simple, please elaborate." << endl;
result = false;
else if (task.size() > 50) {
cout << "Task too detailed. Only 30 chars allowed." << endl;
result = false;

if (date == "02/20/93") {
date = "My birthday!";

return result;


As you can see I'm able to use string and ostream objects without declaring the use of a namespace or particular file. Obviously this means that Global.h is drawing the information from somewhere else, but I'm curious as to where this information is coming from? I always thought that a header file will only reconize code from other files if they've been included with the #include directive in the file itself, so I'm not sure how this is happening and am curious to know what's going on.

Answer Source

No. It's just that whatever is including this Global.h header file must be already #includeing all the required headers.

Somewhat of a simplication: an #include statement gets replaced by logically inserting the contents of the #included file in place of the #include statement itself. When you compile a translation unit, all #include statements are processed in this manner. As if all #include statements get logically replaced by the contents of the referenced file. The final result is a single logical source file, a translation unit, that gets compiled from start to finish.

So, if after all #include statement are processed in this manner, as long as the requisite header files, <iostream>, and others, get logically inserted in the logical translation unit prior to the classes and other resources from <iostream> that are referenced from this header file, this translation unit will compile without issues. Whether it's the same header file that #includes the required header files, <iostream> and others; or some other header file that gets #included earlier, which #includes these header files; it doesn't matter.

It is true that good practice indicates that each file should explicitly #include its prerequisites. But if it doesn't, as long as some other header file has already been #included, the translation unit will still compile.