Why does omission of “#include ” only sometimes cause compilation failures?

If you use members that are declared inside the standard header string then yes, you have to include that header either directly or indirectly (via other headers).

Some compilers on some platforms may on some time of the month compile even though you failed to include the header. This behaviour is unfortunate, unreliable and does not mean that you shouldn’t include the header.

The reason is simply that you have included other standard headers which also happen to include string. But as I said, this can in general not be relied on and it may also change very suddenly (when a new version of the compiler is installed, for instance).

Always include all necessary headers. Unfortunately, there does not appear to be a reliable online documentation on which headers need to be included. Consult a book, or the official C++ standard.

For instance, the following code compiles with my compiler (gcc 4.6):

#include <iostream>

int main() {
    std::string str;
}

But if I remove the first line, it no longer compiles even though the iostream header should actually be unrelated.

Leave a Comment