Why does omission of "#include <string>" 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.


It is possible that other headers that you do include have #include <string> in them.

Nonetheless, it is usually a good idea to #include <string> directly in your code even if not strictly necessary for a successful build, in case these "other" headers change - for example because of a different (or different version of) compiler / standard library implementation, platform or even just a build configuration.

(Of course, this discussion applies to any header, not just <string>.)


Although, there is no direct occurence of #include <string> in a particular source file, doesn't mean it hasn't been included by another header file. Consider this:

File: header.h

#if !defined(__HEADER_H__)
#define __HEADER_H__

// more here
#include <string>
// ...and here

#endif

File: source1.cc

#include <string>

void foo()
{
    // No error here.
    string s = "Foo";
}

File: source2.cc

#include <header.h>

void bar()
{
    // Still no error, since there's a #include <string> in header.h
    string s = "Bar";
}

File: source3.cc

void zoid()
{
    // Here's the error; no such thing as "string", since non of the
    // previous headers had been included.
    string s = "Zoid";
}