Globals

Eww i know, globals...

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.
Last edited on
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.

globals.h
1
2
3
#pragma once

extern int globalInt;


globals.cpp
1
2
// nothing needs to be #included
int globalInt;


main.cpp
1
2
3
4
5
6
7
#include <iostream>
#include "globals.h"

int main()
{
    std::cout << globalInt << std::endl;
}


Be sure to compile both cpp files, not just main.cpp.
Last edited on
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
extern int 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.
1
2
3
4
5
6
class foo {
    public:
    static int Globalnum;
    foo() { ++Globalnum; }
    ~foo() { --Globalnum; }
}

Ive updated my code to
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//Globals.h
enum Directions { Left, Right, None }
extern Directions Dirs;

//Globals.cpp
#include "Globals.h"

Direction Dirs = None;

//Class.h
#include "Globals.h"
class foo {
void FuncThatUsesGlobal();
};

//main.cpp
#include "Class.h"
//omitted
foo Foo;
Dirs = Left;
Foo.FuncThatUsesGlobal();

But that duplicates it even more
Topic archived. No new replies allowed.