错误 C1083:无法打开包含文件:'stdafx.h'

当我编译这个程序时(来自 C++ 编程语言第 4 版):

When I compiled this program (from C++ Programming Language 4th edition):

main.cpp

#include <stdafx.h>
#include <iostream>
#include <cmath>
#include "vector.h"
using namespace std;

double sqrt_sum(vector&);

int _tmain(int argc, _TCHAR* argv[])
{
    vector v(6);
    sqrt_sum(v);
    return 0;
}

double sqrt_sum(vector& v)
{
    double sum = 0;
    for (int i = 0; i != v.size(); ++i)
        sum += sqrt(v[i]);
    return sum;
}

vector.cpp

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

vector::vector(int s)
:elem{ new double[s] }, sz{ s }
{
}
double& vector::operator[](int i)
{
    return elem[i];
}
int vector::size()
{
    return sz;
}

vector.h

#include <stdafx.h>
class vector{
public:
    vector(int s);
    double& operator[](int i);
    int size();
private:
    double* elem;
    int sz;
};

它给了我这些错误:

我在 Windows 7 上的 Microsoft Visual Studio 2013 上运行它.如何修复它?

I run it on Microsoft Visual Studio 2013, on Windows 7. How to fix it?

推荐答案

您必须正确理解什么是stdafx.h",也就是预编译头文件.其他问题或维基百科会回答这个问题.在许多情况下,可以避免使用预编译头文件,尤其是当您的项目很小且依赖项很少时.在您的情况下,因为您可能从模板项目开始,它被用来包含 Windows.h 仅用于 _TCHAR 宏.

You have to properly understand what is a "stdafx.h", aka precompiled header. Other questions or Wikipedia will answer that. In many cases a precompiled header can be avoided, especially if your project is small and with few dependencies. In your case, as you probably started from a template project, it was used to include Windows.h only for the _TCHAR macro.

然后,预编译头通常是 Visual Studio 世界中的每个项目文件,因此:

Then, precompiled header is usually a per-project file in Visual Studio world, so:

  1. 确保您的项目中有stdafx.h"文件.如果您不这样做(例如您删除了它),只需创建一个新的临时项目并从那里复制默认项目;
  2. #include 更改为 #include "stdafx.h".它应该是一个项目本地文件,而不是在包含目录中解析.
  1. Ensure you have the file "stdafx.h" in your project. If you don't (e.g. you removed it) just create a new temporary project and copy the default one from there;
  2. Change the #include <stdafx.h> to #include "stdafx.h". It is supposed to be a project local file, not to be resolved in include directories.

其次:不建议将预编译的头文件包含在您自己的头文件中,以免混淆可以将您的代码用作库的其他源的命名空间,因此将其完全删除在 vector.h 中.

Secondly: it's inadvisable to include the precompiled header in your own headers, to not clutter namespace of other source that can use your code as a library, so completely remove its inclusion in vector.h.

相关文章