Pavlo Zvarych Pavlo Zvarych - 1 year ago 160
C++ Question

Global variables in Qt 5.3

In Visual Studio 2012 (C++) it is enough to declare variable at the beginning for it to have global scope and at the same time set the value for the variable. How to create global variable and initialize in Qt 5.3?

I tried to declare it in header file, but I have a problem: "only static const integral data members can be be initialized within a class".

Thanks in advance!

Answer Source

Global Variables

To create a "global" variable, you need to make it available to everyone and you need to make it declared once, and only once.

globals.h

#ifndef GLOBALS_H
#define GLOBALS_H

#include <qtglobal.h>

// ALL THE GLOBAL DECLARATIONS

// don't use #include <QString> here, instead do this:

QT_BEGIN_NAMESPACE
class QString;
QT_END_NAMESPACE

// that way you aren't compiling QString into every header file you put this in...
// aka faster build times.

#define MAGIC_NUM 42

extern qreal g_some_double; // Note the important use of extern!
extern QString g_some_string;

#endif // GLOBALS_H

globals.cpp

#include "globals.h"
#include <QString>

// ALL THE GLOBAL DEFINITIONS

qreal g_some_double = 0.5;
QString g_some_string = "Hello Globals";

Now at the top of any file you want access to these dangerous global variables is:

#include "globals.h"

// ...

// short example of usage

qDebug() << g_some_string << MAGIC_NUM;

g_some_double += 0.1;

In summary, globals.h has all the prototypes for your global functions and variables, and then they are described in globals.cpp.

public static member variables and methods

For these they are similar to the above example, but they are included in your class.

myclass.h

class MyClass
{
    public:
    static int s_count; // declaration
}

myclass.cpp

int MyClass::s_count = 0; // initial definition

Then from any part of your program you can put:

qDebug() << MyClass::s_count;

or

MyClass::s_count++;// etc

DISCLAIMER:

In general globals and public static members are kind of dangerous/frowned upon, especially if you aren't sure what you are doing. All the OOP goodness of Objects and Methods and Private and Protected kind of go out the window, and readability goes down, too. And maintainability can get messy. See the more in depth SO answer below:

Are global variables bad?

QSettings

For some global settings, I've used QSettings with great success.

http://qt-project.org/doc/qt-5/QSettings.html#details

https://stackoverflow.com/a/17554182/999943

Hope that helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download