I'm trying to declare a structure definition in a header file so I can use the structure in other files, however I get the error:
error C2011: 'Points' : 'struct' type redefinition
from the file where the structure definition is declared. The structure is only defined in that header file.

This is all of the code in the header file:

struct Points {
int xCoordinate; 
int yCoordinate; 
int zCoordinate;
}; // end of struct Points definition

The name of the header file is StructPoints.h and there is no accompanying C++ file.

Also, this header is used in other files source and header files. If I include the header in a file called Test.h, would I also need to include it in a file called Test.cpp?

And is there anything else I need to add to make this header work?

7 Years
Discussion Span
Last Post by ArkM

You might want to put code guards in that header file to prevent the problem you describe.

#ifndef POINTS_H
#define POINTS_H
struct Points {
int xCoordinate; 
int yCoordinate; 
int zCoordinate;
}; // end of struct Points definition

Dear TheBattlizer,
I think you could declare 2 structures with same name. If you include Test.h into file Test.cpp, you don't need to include StructPoints.h into file Test.cpp when it included into file Test.h


Try to understand the standard compilation process logic.

Simplified translation process description:

1. Every .cpp file is processed separately (as if no other cpp files)

2. Preprocessor stage: process all # directives. Every active (see AD's post, #ifdef/#ifndef directives) #include directive in .cpp file is replaced by referred .h (or other) file or header (named in angle brackets) contents (recursively, until all includes are replaced)

3. This is a translation unit text. It's compiled.

Now consider your case. You have Points definition in structpoints.h file. You have #include "structpoints.h" in test.h file. You have #include "structpoints.h" and #include "test.h" directives in test.cpp. Now try to compile test.cpp - see points above:

1. Get test.cpp
2. Replace #include "structpoints.h" . It's Points definition. Replace #include "test.h" to its contents and recursively replace yet another #include "structpoints.h" ! That's yet another Points definition in this translation unit - you breaks "one definition" rule.

No magics...

Now try to understand AD's solution of the problem.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.