clang complaint on missing previous extern
In my code I have found the warning below for the declaration of a global variable.
I know the drawbacks of global variables and use them scarcely. I have the variable also in another cpp file with an extern, but not here.
IIRC in early times we could/did not initialize immediately, but that is handy and avoids duplication. The statement above has been introduced just to check if one of the examples found by google from tutorials will be digested without warning by cland model. However, see yourself.
I do not really see what I should do differently?
Certainly I can make it part of a class and declare as static,but sounds odd to me.
For those fellows checking it out.
I am on windows 10 64 bit
Creator is released 4.7.0
Code model is also for 4.7.0
The extern declaration has to be in a header file, which is then included in all cpp files which use the variables. If the extern declaration is in a cpp file, that declaration is only visible within that cpp file (a.k.a., in that translation unit).
If you only need the variable within the cpp file, declare it in the cpp file as static. If you need it shared between translation units, declare it in a header file as extern, and then include that header and declare the variable in each cpp file (without extern), as you have above.
In general, though, most of the time the presence of a global variable in C++ is a leftover from C-style programming from the days of yore, and indicates a design flaw that will only cause more issues down the line. If the message handler is required throughout the program, create it in your main() function and pass it to objects that depend on it using dependency injection. Likewise, if you need to monitor some kind of global status, it's much more preferable to do it within a relevant class, or even create a new one (e.g. StatusMonitor).
Thanks for response.
You are completely right. Obviously I did not see the forest in front of trees at that time ;)
You may consider using Q_GLOBAL_STATIC, too https://doc.qt.io/qt-5/qglobalstatic.html#Q_GLOBAL_STATIC
And if you are using the message handler for logs, you don't have to have anything global/static - just use qInstallMessageHandler and then qDebug() can be used to operate on your custom message handler.
Thanks for the hint. Looks interesting.