0

I have a total of three classes...
1. Source.cpp (Where the main function is.)
2. Variables.h (Where I declared all my variables in, Variables.cpp is pretty much irrelevant)
3. Functions.cpp & .h (Where I make the functions to run in the main function in Source.cpp)

In main i have this

#include <iostream>
#include <cstdlib>
#include "Variables.h"
#include "Functions.h"
#include <ctime>
using namespace std;

    Variables vari;
    Functions func;

int main(){  
cout << "\n\n>>> ";
        cin >> vari.answer;
        func.choiceChecker();
}

In Functions.cpp I have this

    Variables vari;  
void Functions::choiceChecker(){

        if (vari.answer == 1){
            scenario1();
        }
        else{
            cout << "Failed";
        }
    }

I always get the output failed, instead of running the scenario1 function. I also get two errors.

1.Error 1 error LNK2005: "class Variables vari" (?vari@@3VVariables@@A) already defined in Source.obj C:\Users...\Desktop\Projects\ConsoleApplication1\ConsoleApplication1\Functions.obj ConsoleApplication1

2.Error 2 error LNK1169: one or more multiply defined symbols found C:\Users...\Desktop\Projects\ConsoleApplication1\Debug\ConsoleApplication1.exe ConsoleApplication1

I've tried using a new object in Functions.cpp, i get no errors but it doesn't get the same value from

   cin >> vari.answer;
anony
  • 15
  • 3
  • 2
    It would seem [**this question**](http://stackoverflow.com/questions/15841495/the-usage-of-extern-in-c) may be helpful, though I strongly suggest avoiding globals if at all possible. – WhozCraig Nov 10 '14 at 03:52
  • I suggest not declaring all of your variables in a header. Keep things as local as you can. Make use of parameters and return values and classes. – chris Nov 10 '14 at 03:53
  • 1
    Use the keyword `extern` to refer to a variable already declared in another source (.cpp) file (usually we call these files *translation units*). – didierc Nov 10 '14 at 03:57

1 Answers1

0

To use one global variable, you have to declare it once, then define it once (WhozCraig linked this question with its explanation).

The following should work in your situation:

  • Add extern Variables vari; in Variables.h (below the declaration of the Variables class or struct).
  • At the bottom of Variables.cpp add Variables vari;
  • In Functions.h you add #include Variables.h
  • In Source.cpp you remove #include Variables.h (because Functions.h already includes this)

Now you should be able to use vari in both Functions.cpp and Source.cpp.

Community
  • 1
  • 1
DoubleYou
  • 1,057
  • 11
  • 25