Global objects in seperate file

I'm trying to make a simple program that uses global class objects. The only problem is that I can't seem to define them in a separate file. eg:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
"classA.h"
Class classA
{
    public:
        int x;
        int y;
    private:
        int getX(){return x;};
        int getY(){return y;};
}objectA;

"main.cpp"
#include "classA.h"

void main()
{
    objectA.getX();
}


That's basically how I'd like my program to work, but it throws out an error every time. I'm not 100% sure of the exact error, but it's something like "objectA already defined in main.cpp"

Is it possible to do this? Or do I have to declare global objects in the main file?
Last edited on
either
1
2
//class.h
class A{ ... };

1
2
3
//class.cpp
#include "class.h"
A object;

1
2
3
4
//main.cpp
#include "class.h"
extern A object
int main{ ... }


or
1
2
3
4
5
//class.h
class A{ ... };
class Global{
   static A object;
};

1
2
3
//class.cpp
#include "class.h"
A Global::object;

1
2
3
//main.cpp
#include "class.h"
int main(){ ... } // note that to access object now you have to write Global::object 


the second one is preferred.
The use of the object seems to only be in main, so defining the object in main will suffice. No need for overkill....
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
"classA.h"
Class classA
{
    public:
        int x;
        int y;
    private:
        int getX(){return x;};
        int getY(){return y;};
}; // <-- don't create the object here

"main.cpp"
#include "classA.h"

void main()
{
    classA objectA; // <-- now it'll only be defined in main
    objectA.getX();
}


If you need to use it outside of main, pass it as a parameter. No need for a global variable.

-- edit: but if you absolutely have to have the global, then you can do like hamsterman
Last edited on
Thanks to both of you! Great help!
Topic archived. No new replies allowed.