Solved Regarding to the main.cpp file using global vars
In the image, I have declared a simple int x var at line 15, but I have got a warning telling me that :
<<a previous extern declaration for non-static variable 'x'>>
My apologies, it is the first time I see this error, previously I only worked using console applications and have set many different types of variables before the main() entry, never seen this before...
What is happening?
Thanks so much!.
JonB last edited by JonB
For what you want (probably), put
staticin front of it:
static int x;
Nothing about your question has anything to do with whether your program is console/UI/Qt or not, nor whether it's in
main()or anything. Maybe you're using a different compiler/warnings from whatever you're used to.
BTW, don't know what compiler you're using (always worth stating for a compilation question!), but can't you click on that warning and Google/read up on it? Something somewhere will explain why it's warning and what you can do about it.
And just so you do not get tempted.
No Global Qt objects allowed.
No Qt object may be created before QApplication in main.
The warning comes from the Clang Code Model, telling you that the variable is visible in your whole program at link time, but cannot be accessed from other source files as there is no extern declaration before.
As said before,
staticis most likely what you want here.
All clear!.. thanks so much all..
JonB last edited by
Now that this thread is solved:
cannot be accessed from other source files as there is no extern declaration before.
Purely, purely OOI: in C another source file, which happens to know the variable name, can do its own
extern int x;and then access that variable. Does C++ forbid that, you cannot access the first file's
xunless it chooses to
externit in its header file?
Purely, purely OOI: in C another source file, which happens to know the variable name, can do its own extern int x; and then access that variable. Does C++ forbid that, you cannot access the first file's x unless it chooses to extern it in its header file?
I think not. However, even in C it is better to put extern in a header. Otherwise the declarations might differ - I had that recently and it caused strange bugs (variable size was wrong which led to overlapping variables, IIRC)
JonB last edited by JonB
Oh, I never meant it was a good idea! I was questioning whether you/the error message were implying that it was now compulsory/forbidden, sounds like it's as-was.
@JonB as said, I'm not sure.
I just wanted to give an example of why it might be a bad idea.
In case someone doesn't want to repeat my fails...