2

I expect this is incredibly simple but can't for the life of me figure out whats wrong. I'm new to C++ and I've created a C++ class in visual studio and am trying to use it in the main method of another file. I've stripped everything back to the bare minimum but still I can't get it to run. The first compile error I get is 'Test': undeclared identifier. If I remove 'Test test;' from App.cpp it all compiles fine. Below is the code. Can anybody help?

App.cpp:

#include "Test.h"
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
#include <fstream>

using namespace std;

int main()
{
    Test test;
    //cout << test.getNumber() << endl;
    return 0;
}

Test.h:

#pragma once
class Test
{
private:
    int number;

public:
    int getNumber();
    Test();
    ~Test();
};

Test.cpp:

#include "stdafx.h"
#include "Test.h"


int Test::getNumber()
{
    return number;
}

Test::Test()
{
    this->number = 1;
}


Test::~Test()
{
}
Steve W
  • 1,108
  • 3
  • 13
  • 35
  • 2
    Place this include #include "Test.h" after this #include "stdafx.h" – Vlad from Moscow Dec 20 '17 at 17:13
  • 2
    Visual studio does not compile anything before `#include "stdafx.h"`, if using precompiled headers. – Gaurav Sehgal Dec 20 '17 at 17:14
  • 1
    The problem is that VS defaults to using the "precompiled headers" feature of Visual C++, which makes the preprocessor behave in decidedly non-standard ways. One fix is as @VladfromMoscow notes, to let the precompiled header (here `"stdafx.h"`) be the first include in every implementation file. A better solution is to just **turn off precompiled headers** in the project settings. Right-click project → Properties → turn it off. There. – Cheers and hth. - Alf Dec 20 '17 at 17:17
  • Really? That was it... Well I did say it must be simple. Thanks – Steve W Dec 20 '17 at 17:22

1 Answers1

0

The problem is that "stdafx.h" is pre-compiled. Visual c++ will not compile anything before the #include "stdafx.h" in the source file, unless the compile option /Yu'stdafx.h' is unchecked (by default); it assumes all code in the source up to and including that line is already compiled.

The solution is to move it to be the first include.

You can read more about it in the wiki page of Precompiled header.

Mixhab
  • 421
  • 3
  • 14