Repeated Multiple Definition Errors from including same header in multiple cpps

Since you’re declaring those variables in the header file, and including the header file in each C++ file, each C++ file has its own copy of them.

The usual way around this is to not declare any variables within header files. Instead, declare them in a single C++ file, and declare them as extern in all the other files that you might need them in.

Another way I’ve handled this before, which some people might consider unpleasant… declare them in the header file, like this:

#ifdef MAINFILE
    #define EXTERN
#else
    #define EXTERN extern
#endif

EXTERN MYSTRUCT Job_Grunt;
EXTERN MYSTRUCT *Grunt = &Job_Grunt;
EXTERN MYSTRUCT Job_Uruk;
EXTERN MYSTRUCT *Uruk = &Job_Uruk;

Then, in one of your C++ files, add a…

#define MAINFILE

…before your #include lines. That will take care of everything, and is (in my personal opinion) a lot nicer than having to redeclare all of the variables in every file.

Of course, the real solution is not to use global variables at all, but when you’re just starting out that’s hard to achieve.

Leave a Comment