Matrix21 Matrix21 - 8 days ago 5
C++ Question

Global variable error C++

I'm having an error I don't know how to fix in my large Operating Systems homework. The error I'm getting is "42 duplicate symbols for architecture x86_64". I presume this is to do with my global variables file "global.h". I have 3 global variables I use and "global.h" is included in an abstract class called "PageReplacementAlgorithm.cpp". I have around 6 classes that are derived from the PageReplacementAlgorithm class and they utilize these global variables. I think the problem comes in when I include all these derived classes in my "main.cpp" as I need to make new instances of them. How can I fix the implementation of the global variables?

Global.h

#include "PageTableEntry.h"
using namespace std;
#ifndef Global_H
#define Global_H

extern PageTableEntry pageTable[64];
extern int* frameTable;
extern int framesCount;

#endif


PageReplacementAlgorithm.h

#include "Global.h"
using namespace std;

#ifndef PageReplacementAlgorithm_H
#define PageReplacementAlgorithm_H

class PageReplacementAlgorithm {
public:
virtual int selectFrame(PageTableEntry &p) = 0;
};

#endif


Example Derived Class (FIFO)

include "PageReplacementAlgorithm.h"
using namespace std;

#ifndef FIFO_H
#define FIFO_H

class FIFO : public PageReplacementAlgorithm {
public:
FIFO();
int selectFrame(PageTableEntry &p);
private:
int entries;
};

#endif


Main.cpp

#include "Aging.cpp"
#include "Clock.cpp"
#include "FIFO.cpp"
#include "MMU.cpp"
#include "NRU.cpp"
#include "Random.cpp"
#include "SecondChance.cpp"

Answer

Why do you include all cpp files in main.cpp? I think they contain same includes, right? Even you have the guards there, you do additional includes before that guards and that is probably the source of problems. The main.cpp could contain just main() function and import headers of your classes, there is no need to include cpp.

Also, you can modify your header files to look like this (for sake of extreme safety):

#ifndef PageReplacementAlgorithm_H
#define PageReplacementAlgorithm_H
#include "Global.h"
using namespace std;

...
#endif

I recommend you to look at answer C++ #include guards

Comments