Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get compilation errors after I conditionally include stdafx.h?

I'm trying to write a program that compiles in Borland C++ and Visual C++. To do this, I add #ifdef _MSC_VER to include the stdafx.h file when the source is compiled under VS. The code compiles and executes OK in Borland C++, but in VS, it fails:

error C1020: unexpected #endif

#ifdef _MSC_VER //I'm in VS
#include "stdafx.h"
#endif //this line doesn't compile in VS


#ifdef __BORLANDC__   //I'm in Borland
#pragma hdrstop
#pragma argsused
#endif

#include <iostream>

int main(int argc, char* argv[])
{
    std::cout << "Hello" << std::endl;
    std::cin.get();
    return 0;
}

How I can fix this error?

like image 610
Salvador Avatar asked Oct 18 '11 02:10

Salvador


1 Answers

The way MSVC implements precompiled headers, is basically that the compiler ignores everything up to the line that brings in the precompiled header, and starts over from scratch there. So when you compile your program, it doesn't "remember" the #ifdef line, so the #endif line makes no sense to it.

The thing is, there's nothing inherently "MS" about stdafx.h, beyond the peculiar naming scheme [which you can change anyhow]. So why bother blocking out the inclusion in Borland in the first place? Worst case scenario, you move the _MSC_VER block into the header, and you end up in the same situation you're in now, except there's a single wasted include file. Or you let your build system redirect the #include to a Borland-specific stdafx.h file.

like image 179
Dennis Zickefoose Avatar answered Oct 12 '22 23:10

Dennis Zickefoose