在有条件地包含stdafx.h之后,为什么会出现编译错误?

Sal*_*dor 8 c++ compiler-errors c++builder conditional-compilation visual-studio

我正在尝试编写一个用Borland C++和Visual C++编写的程序.为此,我在VS下编译源时添加#ifdef _MSC_VER包含stdafx.h文件.代码在Borland C++中编译并执行OK,但在VS中,它失败了:

错误C1020:意外#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;
}
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个错误?

Den*_*ose 12

MSVC实现预编译头的方式基本上是编译器忽略了引入预编译头的行的所有内容,并从头开始.因此,当您编译程序时,它不会"记住"该#ifdef行,因此该#endif行没有任何意义.

问题是,stdafx.h除了特殊的命名方案[无论如何你可以改变]之外,没有任何内在的"MS" .那么为什么要首先阻止在Borland中加入?在最糟糕的情况下,您将_MSC_VER块移动到标题中,最终会出现与您现在相同的情况,除非有一个浪费的包含文件.或者,您让构建系统将重定向#include到Borland特定的stdafx.h文件.