Reputation: 585
One of the header files is as follows -
#include "stdafx.h"
class AAA
{
public:
std::string strX;
std::string strY;
};
When I try to compile the project, I get the error
error C2011: 'AAA' : 'class' type redefinition
Nowhere else in my program have I redefined the class AAA
. How do I fix this?
Upvotes: 32
Views: 103792
Reputation: 11
There are two ways to go about this but you can't use both. Make sure to wrap the class definition with a compiler directive that the class declaration only gets compiled once:
#include "stdafx.h"
#pragma once
class AAA{
public:
std::string strX;
std::string strY;
};
-or-
#include "stdafx.h"
#ifndef AAA_HEADER_
#define AAA_HEADER_
class AAA
{
public:
std::string strX;
std::string strY;
};
#endif
Also: note the class import statement should be at the top of your file.
Upvotes: 1
Reputation: 154
I met this problem today in VS 2017. I added #pragma once
, but it didn't work until I added a macro definition:
// does not work
#pragma once
// works with or without #pragma once
#ifndef _HEADER_AAA
#define _HEADER_AAA
//
// my code here....
//
#endif
I have no clue how to explain this, but it is a solution for me.
Upvotes: 1
Reputation: 5434
Adding
#pragma once
to the top of your AAA.h file should take care of the problem.
like this
#include "stdafx.h"
#pragma once
class AAA
{
public:
std::string strX;
std::string strY;
};
Upvotes: 39
Reputation: 10425
In addition to the suggested include guards you need to move #include "stdafx.h" out of the header. Put it at the top of the cpp file.
Upvotes: 5
Reputation: 10979
Change to code to something like this:
#ifndef AAA_HEADER
#define AAA_HEADER
#include "stdafx.h"
class AAA
{
public:
std::string strX;
std::string strY;
};
#endif
If you include this header file more than once in some source file, include guards will force compiler to generate class only once so it will not give class redefinition
error.
Upvotes: 59