views:

1348

answers:

5

I'm using Qt and in the main method I need to declare an object that I need to use in all my other files. How can I access that object in the other files? (I need to make it global..)

I'm use to iPhone development and there we have the appDelegate that you can use all over the application to reach objects you've declared in applicationDidFinishLaunching method. How can I do the same in Qt?

+1  A: 

global_objects.hpp

extern int myGlobalInt;

global_objects.cpp

#include "global_objects.hpp"

namespace
{
    int myGlobalInt;
}

And then #include "global_objects.hpp" in every place you need myGlobalInt.

You should read C++ singleton vs. global static object and Initializing qt resources embedded in static library as well.

Piotr Dobrogost
You forgot the `extern` keyword in the .hpp file -- this will instanciate `myGlobalInt` each time the hpp is included
bluebrother
Yep
Piotr Dobrogost
A: 

In general, you shouldn't use global variables in object oriented programming. In your case, you can solve the problem by providing static access functions to the variable in your main class. You should be aware, though, that this is somewhat contrary to OOP.

class MainClass
{
    public:
        static int mySharedValue(void) { return m_mySharedValue; }
        static void setMySharedValue(int value) { m_mySharedValue = value; }
    private:
        int m_mySharedValue;
}

Foo::myOtherClassFunction(void)
{
    // do something
    int bar = MainClass::mySharedValue();
    // do some more
}

Furthermore, you can derive your main application from QApplication and add the access functions there, accessing the main object through the qApp pointer provided by Qt. Additionally to that you can always use a global variable the same way you can do in C, though I wouldn't recommend that.

bluebrother
My idea to use the global object was because this object will hold data that I need in almost each widget and that data is fetched from the database. If I don't use a global object I need to access the database each time the object is instanced. I thought it was better to just get it once, is that the wrong idea?
Martin
A: 

You can use the singleton pattern. There are also sample codes in wikipedia.

erelender
+1  A: 

In Qt there is the singleton QApplication, with its static method QApplication::instance() which gives you the one and only QApplication object back. It has many other static member functions (in an earlier age they were called "globals"), for the mainwindow, the active window etc.

http://doc.trolltech.com/4.5/qapplication.html

You can sublass it if you want to add your own statics.

drhirsch
A: 

Q_GLOBAL_STATIC might help - more info here: http://delta.affinix.com/2006/01/31/q_global_static/

Dave