ifndef isn't working; I have a header file included twice

626 Views Asked by At

My Ifndef isn't working. I have MapData.h included twice in both: Generate.cpp and Risky Strats.cpp

MapData.h:

#ifndef MAPDATA
#define MAPDATA
#include <iostream>
#include <vector>
class bases {
public:
    int x;
    int y;
};

class field {
public:
    std::vector <bases> map;
};
field battleground;
#endif //MAPDATA

Generate.cpp:

#include <stdlib.h>//Randomness
#include <time.h>//time
#include <math.h>
#include "MapData.h"

Risky Strats.cpp:

#include <SFML/Graphics.hpp>
#include "MapData.h"

I keep getting the same error: class field battleground" (?battleground@@3Vfield@@A) already defined in Generate.obj

2

There are 2 best solutions below

0
On

The "dance of the ifdefs" stops you including the same .h multiple times in one .cpp. You only include it once per .cpp file, but you include it in two different .cpp files which means both of those .cpp files have the global variable battleground.

You could extern the variable declaration in the .h and put the definition into one of the .cpp files (or MapData.cpp) but I'd start by questioning whether having a global variable is the right design choice in the first place.

0
On

That's not how include guards work - they prevent against multiple inclusion of the same header file in a single translation unit, not across multiple translation units.

As you have it now, each of your translation units gets a global object called battleground, and then there's a collision at link time.

If in fact you want a single global field battleground, you need to add extern to field battleground; in your header, then take the definition field battleground; and put it in exactly one of your .cpp files.