I have created a new .h file with the following contents:
#include "stdafx.h"
#include <string>
using namespace std;
struct udtCharVec
{
wstring GraphemeM3;
wstring GraphemeM2;
};
When I want to compile it, the compiler tells me "error C2011: udtCharVec: struct type redefintion".
I did a text search, and I don't have "struct udtCharVec" defined anywhere else.
Does anybody see where I went wrong?
You are probably including this header file more than once in a single translation unit. When the file is included for the second time, struct udtCharVec
has already been defined, and so you get a "type redefinition" error.
Add an include guard. After the first inclusion, CharVec_H
will be defined, and so the rest of the file will be skipped:
#ifndef CharVec_H
#define CharVec_H
#include "stdafx.h"
#include <string>
using namespace std
struct udtCharVec
{
wstring GraphemeM3;
wstring GraphemeM2;
};
#endif
Say your project consisted of three files. Two header files and one source file:
CharVec.h
#include "stdafx.h"
#include <string>
using namespace std
struct udtCharVec
{
wstring GraphemeM3;
wstring GraphemeM2;
};
CharMatrix.h
#include "CharVec.h"
struct udtCharMatrix
{
CharVec vec[4];
};
main.cpp
#include "CharVec.h"
#include "CharMatrix.h"
int main() {
udtCharMatrix matrix = {};
CharVec vec = matrix.vec[2];
};
After the preprocessor had run, main.cpp would look like this (ignoring standard library includes):
//#include "CharVec.h":
#include "stdafx.h"
#include <string>
using namespace std
struct udtCharVec //!!First definition!!
{
wstring GraphemeM3;
wstring GraphemeM2;
};
//#include "CharMatrix.h":
//#include "CharVec.h":
#include "stdafx.h"
#include <string>
using namespace std
struct udtCharVec //!!Second definition!!
{
wstring GraphemeM3;
wstring GraphemeM2;
};
struct udtCharMatrix
{
CharVec vec[4];
};
int main() {
udtCharMatrix matrix = {};
CharVec vec = matrix.vec[2];
};
This expanded file include two definitions of struct udtCharVec
. If you add an include guard to CharVec.h
, the second definition will be removed by the preprocessor.