I need a global to be accessible to multiple files
Right now i have this
1 2 3 4 5 6
//class.h
#include "Globals.h"
class foo {
public:
void FunctionThatUsesAGlobal();
};
1 2 3 4 5 6
//main.cpp
#include "class.h"
//bla bla bla
foo Foo;
Globalenum = left;
Foo.FunctionThatUsesAGlobal();
I keep getting a duplication error in the linking phase. I tried declaring the global as extern in the global header file and then implementing it in the main file then declaring it extern in the foo header file but that still didnt work.
Should work, declaring them extern in the header that uses them (or the Globals.h header for convenience). Just remember, the definition must go in a cpp file, not a header.
If you do this, Globalnum is available to anything that includes the Globals.h file. You do not need to redefine it in any other file (other than the single implementation file).
1 2
// Globals.h
externint Globalnum;
1 2 3 4 5 6 7 8 9
//main.cpp
int Globalnum;
void some func()
{
foo Foo;
Globalnum = left;
Foo.FunctionThatUsesAGlobal();
}
That being said, why do you need a global? If you are trying to keep track of the number of Foo's that are being created, you can use a static variable. When you use the static keyword, the label is effectively the same as a global, but is limited in scope. The Globalnum here will occupy the same space in memory regardless of how many instances of foo are open. That means that they all read from and write to the same label.