30

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?

meJustAndrew
  • 6,011
  • 8
  • 50
  • 76
user3164272
  • 565
  • 1
  • 9
  • 20

5 Answers5

55

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.

Ashot
  • 10,807
  • 14
  • 66
  • 117
37

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;
};
empty
  • 5,194
  • 3
  • 32
  • 58
5

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.

ScottMcP-MVP
  • 10,337
  • 2
  • 15
  • 15
1

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.

Yun
  • 3,056
  • 6
  • 9
  • 28
0

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.