Creris
Creris

Reputation: 1128

C++ global variable in multiple files

I have a Class Button, that includes a class ButtonManager, which managers buttons.

Then I have 2 functions that handle things, 1 is like login window with few buttons, the second one is the game menu itself, which also has buttons in it.

However, the two windows take quite a lot of lines, and so I decided to split it to multiple .cpp files, where I just call stuff from main.

The problem is, I need to include the button class in both .cpps, and main and the secondary cpp also include some dummy.h which contains the declaration of the common function rendering the menu.

The main issue is, that the ButtonManager has a global variable and when compiling it says that the symbol is already defined.

Example code:

a.h(acts as if it was the Button Manager header file):

#ifndef _ABC_
#define _ABC_

struct A{
    int b;
}a = A();

#endif

side.h(lets say this is for main game window):

#ifndef _SIDE_H_
#define _SIDE_H_

int callSomething();

#endif    //_SIDE_H_:

side.cpp:

#include "side.h"
#include "abc.h"

#include <iostream>

int callSomething()
{
    std::cout << a.b << "\n";
    return a.b;
}

main.cpp:

#include "abc.h"
#include "side.h"
#include <iostream>

int main()
{
    callSomething();
    std::cin.get();
}

When I try to compile it, the compiler complains:

1>side.obj : error LNK2005: "struct A a" (?a@@3UA@@A) already defined in DynamicDispatch.obj 1>H:\Microsoft Visual Studio 11.0\example\Debug\dynamicdispatch.exe : fatal error LNK1169: one or more multiply defined symbols found

All help is appreciated

Upvotes: 1

Views: 881

Answers (1)

clcto
clcto

Reputation: 9648

In a.h declare the variable as

struct A{
    int b;
};
extern struct A a;

Then in main.cpp define it once:

struct A a;
int main()
{
    //...
}

Upvotes: 5

Related Questions