简体   繁体   中英

#include iostream before stdafx.h in c++

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM