#include iostream before stdafx.h in c++

2019-03-07 00:42发布

问题:

I created a C++ Console Application in Visual Studio Community 2017. There is only a main.cpp file in the project. Here is my main.cpp file:

#include <iostream>
#include "stdafx.h"

int main()
{
    std::cout << "hello world!";
    return 0;
}

I get a compilation error that 'cout' is not a member of std. But if I include iostream after stdafx.h, that is,

#include "stdafx.h"
#include <iostream>

int main()
{
    std::cout << "hello world!";
    return 0;
}

then it compiles just fine. So why does it not work when I include iostream before stdafx.h?

回答1:

The answer to your question can be found, with a little puzzling, here.

stdafx.h enables precompiled headers. Based on the error given, and the discussion of how Microsoft implements precompiled headers, it seems that the compiler simply starts compiling from the include of stdafx.h forward. So when stdafx.h is placed after iostream, iostream is not included, producing the mysterious error.