Visual Studio including a header before stdafx.h creates errors

564 views Asked by At

Let's assume I have a class 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;
}

For this example, the code compiles. However, if I switch between line 1 and line 2 in TestClass.cpp and include stdafx.h second, for some reason I get the following compilation errors:

'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

Obviously if I just include stdafx.h first I won't have any problems, but I can't seem to understand why this happens. Any help would be appreciated.

1

There are 1 answers

4
Laszlo On

Do the following:

  1. #include <string> into TestClass.h
  2. disable precompiled headers

Then it should work.