next up previous
Next: Member functions Up: Common problems Previous: Unsupported functions.


Memory handling and global variables.

While a lot of work has been done to ensure that gp2c handles global variables properly, the use of global variables is still a lot of trouble, so try to avoid them if you do not understand the implications on memory handling.

First, there is a common practice to use undeclared variables as formal variables, for example we assume x='x and write a*x+b instead of a*'x+b. So gp2c will not raised an undeclared variable to the rank of global variable unless you declare it with the global() command, or you use it at toplevel (i.e. outside any function). See also Section 2.3

Second, global variables seen by a compiled function are C variables, not GP variables. There is no connection between the two. You may well have two variables with the same name and a different content. Currently GP knows only how to install functions, not variables, so you need to write compiled functions in order to access global variables under GP.

Basically, global variables are allocated in the main stack which is destroyed each time GP prints a new prompt. This means you must put all your commands on the same line. Also global variables must be initialized using the init_<filename> function before being used, and are only supported with the -g flag.

So you end up doing gp2c-run -g global.gp

parisize = 4000000, primelimit = 500000
? init_global();myfunction(args);

Note that nothing prevents you from calling init_global in the GP program. In that case, you can omit the parentheses (i.e, write init_global, not init_global()) so that you can still run your noncompiled program.

Another way to handle global variables is to use the clone function which copies a PARI object to the heap, hence avoids its destruction when GP prints a new prompt. You can use unclone to free a clone. Please read the PARI/GP manual for more information about clone.

A good use of clone is for initializing constant variables: for example in test/gp/initfunc.gp, the vector T is initialized by

T=clone([4,3,2,2,1,1,1,1,0,0,0,0,0,0,0,0])
You must still run the init_<filename> after starting GP, but after that you can use T safely.

GP itself currently does not know about clone and unclone, but you can use dummy functions

clone(x)=x
unclone(x)=while(0,)
when running uncompiled.


next up previous
Next: Member functions Up: Common problems Previous: Unsupported functions.
Bill Allombert 2006-01-28