GLOBAL variables in subs - warning, variable already exists

Previous topic - Next topic

doimus

I usually keep my code organized by putting all constants and global definitions in separate SUBs. It kind of makes sense to me to have all related global stuff in one place (in this example type definition and array declaration).

Code (glbasic) Select
GOSUB DefineConstants
GOSUB DefineGlobals

WHILE TRUE
MyFunction()
SHOWSCREEN
WEND


SUB DefineConstants:
CONSTANT ARRSIZE= 100
ENDSUB

SUB DefineGlobals:
TYPE TArray
x;y;z
ENDTYPE
GLOBAL gArr[] AS TArray
DIM gArr[ARRSIZE]
ENDSUB

FUNCTION MyFunction:
// do stuff
ENDFUNCTION


That way, once I'm done with that stuff I can collapse the subs in editor, or even move them to different file, cleaning up the main source file. And since I don't use subs for any other calls, it's very easy to get back to these definitions for modifications, etc.

But GLB compiler puts up a warning for every global variable that's defined in such way as "warning : variable already exists ".
It's not much of a big deal, but when there are lots of those warnings, it's possible to miss some other warning...

bigsofty

GLOBALS and CONSTANTS shouldn't be defined within subs, its bad programming practice since their scope is outside as well as inside the sub. If you want them away from the rest of your code, my advice is to stick them in a separate "Globals.gbas" file and include it with your project.
Cheers,

Ian.

"It is practically impossible to teach good programming style to students that have had prior exposure to BASIC.  As potential programmers, they are mentally mutilated beyond hope of regeneration."
(E. W. Dijkstra)

Slydog

Weird. I'm not sure how subs are handled internally by GLBasic, but GLOBALs should be defined outside of any function or sub, since sub variables aren't global.  But strange it tells you it's already defined . . . well ya, globally I suppose!

I see what you want and I like the collapsing idea.  Maybe we need Gernot to add new custom region commands, like visual studio.  Then we could collapse them at will.  It wouldn't affect the compiler, just the editor.  And now (for a while at least) globals can be moved to any file, which helped my code organization immensely.

Something like:
Code (glbasic) Select
REGION "Global Constants"
CONSTANT ARRSIZE= 100
ENDREGION

REGION "Global Variables"
TYPE TArray
x;y;z
ENDTYPE
GLOBAL gArr[] AS TArray
DIM gArr[ARRSIZE]
ENDREGION


[Edit] Oops, restated a few things bigsofty mentioned.  And I have a main globals file too, which holds global definitions specific for the game code only, then I stick globals in each library file I have that are specific to ONLY that library (Like my camera library has the cull mode constants, not need anywhere else in the project)
My current project (WIP) :: TwistedMaze <<  [Updated: 2015-11-25]