【问题标题】:Visual Studio including a header before stdafx.h creates errors [duplicate]Visual Studio 在 stdafx.h 之前包含标头会产生错误 [重复]
【发布时间】:2017-07-24 23:14:00
【问题描述】:

假设我有一个班级Person

TestClass.h:

#pragma once

class Person {
    int age;
    std::string name;

public:
    Person(int age, const std::string& name);

private: 
    int getAge();
    std::string getName();
};

TestClass.cpp

#include "stdafx.h"
#include "TestClass.h"

Person::Person(int age, const std::string& name) : age(age), name(name) {};

int Person::getAge() {
    return age;
}

std::string Person::getName() {
    return name;
}

对于这个例子,代码编译。 但是,如果我在TestClass.cpp 的第 1 行和第 2 行之间切换并包含 stdafx.h 第二,由于某种原因,我得到以下编译错误:

'Person': is not a class or namespace name  
missing type specifier - int assumed. Note: C++ does not support default-int    
'Person': constructor initializer lists are only allowed on constructor definitions 
'Person': is not a class or namespace name  
'Person': function should return a value; 'void' return type assumed    
'age': undeclared identifier    
'Person': is not a class or namespace name  
'name': undeclared identifier

显然,如果我首先包含 stdafx.h,我不会有任何问题,但我似乎无法理解为什么会发生这种情况。任何帮助将不胜感激。

【问题讨论】:

  • stdafx.h 是一个奇怪的特定于 Visual Studio 的文件,具有特殊的含义和行为:What's the use for “stdafx.h” in Visual Studio? 如果它坚持要先行,那就顺其自然吧。 Visual Studio 不会编译 stdafx.h 之前文件中的任何内容。因为他们这么说。
  • @user4581301 这就是我要找的。我知道 stdafx.h 是一个 VS 特定文件,我认为这可能是故意的,但我找不到任何明确表示在文件包含之前什么都不能出现的东西。谢谢。
  • 与您一起讨论缺乏来自马口的解释。我能做的最好的权威答案是上一个链接
  • 如果你不需要stdafx.h,最好选择empty project,同时新建一个。这样标准 C++ 文件将正常编译而不包括 stdafx.h
  • @LưuVĩnhPhúc 我知道如何让代码编译,问题的关键是我可以理解为什么如果 stdafx.h 不在第一行,代码将无法编译。这是假设需要 stdafx.h。

标签: c++ visual-studio stdafx.h


【解决方案1】:

执行以下操作:

  1. #include 到 TestClass.h
  2. 禁用预编译头文件

那么它应该可以工作了。

【讨论】:

  • 正如我在评论和实际问题中提到的,我知道如何让代码编译。问题不在于如何编译代码,这就是为什么如果 stdafx.h 不在第一行,代码无法编译的原因。
  • 我尝试了您的代码,并且通过这些更改可以正常编译。即使在 TestClass.h 之后包含 stdafx.h
  • 你用什么来编译代码?我使用 VS 2015 并没有编译。如果您使用的是 VS,那么编译的代码没有任何意义,因为 VS 不会编译 stdafx.h 之前的任何内容,除非编译选项 /Yu'stdafx.h' 未选中,如本答案stackoverflow.com/a/16040876/5513449 中所述
  • 我使用的是 VS2013。 '/Yu unchecked' 表示'禁用预编译头文件'。此建议适用于像我这样的懒惰程序员。正确的解决方案是在更改包含文件的顺序后重新创建 .pch 文件,例如通过删除它。重新创建 .pch 文件后,它会编译得很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-21
  • 2012-05-10
  • 2018-04-12
  • 1970-01-01
  • 2020-10-14
  • 1970-01-01
相关资源
最近更新 更多