More classes and extern variable in C++

I've some troubles with linking files together. There are classes which I'm using:

header of class A in file A.h

class A
{
public:
    B someVariable;    //there is class B used!!
    int number;
};

header of class B in file B.h

class B
{
public:
    void someMethod();  
};

implementation of B

B::someMethod()
{
    cout << "Value is:" << globalInstanceOfA.number << "\n";
}

And then in another file I need to declare a global variable globalInstanceOfA, which i will use throughout the whole program...

But I can't solve out where to put include, extern and so on. I've tried something like that:

#include "A.h"
#include "B.h"

extern A globalInstanceOfA;

Can someone help me?

Upvotes: 0

Views: 2396

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

The line

extern A globalInstanceOfA;

goes in a header file that you must include in order to use the variable globalInstanceOfA; this provides a declaration of the global variable.

The line

A globalInstanceOfA;

goes into any of your cpp files to provide a definition for the global variable. There must be exactly one definition among all cpp files in your program.

Upvotes: 1

Related Questions