Forum > Beginners

is there a way to Forward reference a variable?

(1/2) > >>

billd:
I have a main program that uses some of my own units

In the main program, I have a global variable, let's call it  Global_x

I initialize Global_x in the main program at the appropriate time.

I would like to use Global_x in one of the units, however because Global_x is defined after the "uses" clause, the unit does not recognize it.

Is there a way I can make a variable global to all parts of the program?

I am thinking that perhaps I need a unit that just defines the global variables (I only have a couple) so when the program compiles those variables are defined early on.  Is there another way, something like a Forward statement, but not for procedures or functions and only for variables?

Thanks,
- Bill

Curt Carpenter:
I use a "Globals" unit and have found it useful to keep all of my global variables in a single record in that unit.  The record name creates a "name space" that helps me remember that I'm dealing with a variable that is declared in the "Globals" unit.   (I've also found that it is useful to make "Globals" an advanced record so that I convert some of my global variables into properties with associated read and write procedures.)

440bx:
if I have understood your intention correctly, you'd like to declare a variable in the main program and have that variable be accessible/visible in other units the program uses.

If that is what you're trying to do then read the post and the related posts found at https://forum.lazarus.freepascal.org/index.php/topic,53408.msg395353.html#msg395353
that will give you an "alternate" way of having global variables.

billd:
440BX, thanks!

That topic helped and it seems to work. I did try just making a unit for global variables, but that would not let one unit share with another unit and with the lpr main file. The topic using "C" declarations (cvar) seems to work fine.

- Bill

440bx:

--- Quote from: billd on September 27, 2023, 03:54:33 pm ---440BX, thanks!

That topic helped and it seems to work. I did try just making a unit for global variables, but that would not let one unit share with another unit and with the lpr main file. The topic using "C" declarations (cvar) seems to work fine.

- Bill

--- End quote ---
You're welcome.

Keep in mind a potential downside of using the "export/external" method to have global variables, which is, that method can be used anywhere (in any unit) causing the global variables to potentially be scattered everywhere.  A little programming discipline is important to prevent that problem.

Navigation

[0] Message Index

[#] Next page

Go to full version