|
|
|
Initialization and finalization of modules
|
|
20 Initialization and finalization of modules
You often need to initialize module before it is used.
For example to global variables often needs some initial value that
is not constant and so on. Gont uses section declaration
to deal with such cases. section is followed by name of
section. You can use section several times. Bodies of
section under the same name in one module are concatenated,
in order, in which they are given in source code.
Currently just two sections are provided:
-
init
Code in init
section is executed at the beginning of the program.
Order in which init
sections of modules are executed is specified
in command line during link. However Gont linker ensures you do not use
any module, that has init
or fini
section before it is
initialized.
-
fini
Code in fini
section is executed just before leaving the program.
Order of execution of fini
sections is order of init
reversed.
The Std::at_exit
function registers given function to be run
before program exits. However content of all fini
sections are
executed after all functions registered with Std::at_exit
has
completed.
There is no main
function in Gont program. One uses
section init
for this purpose.
Following example:
section init { print_string("1 "); }
section fini { print_string("-1 "); }
section fini { print_string("-2\n"); }
void bye()
{
print_string("bye ");
}
void main()
{
at_exit(bye);
print_string("main ");
}
section init { print_string("2 "); main(); }
prints: 1 2 main bye -1 -2
.
20.1 Greedy linking
You may tell gontc to link given library in greedy mode. It means
that all files from this library are linked, and their init
and
fini
sections are executed.
You don't want to do this with regular libraries, like Gont standard
library, because you do not need all files from them. gontc is wise
enough to tell that you need, let's say List
module, if you
used it in your program.
However greedy linking might come in handy, modules are not explicitly
referenced from main program, but their init
sections registers
them somewhat with the main program.
20.2 Mutually recursive modules
Unlike in Caml, it is possible to have two modules that reference each
other. However none of them can have init
nor fini
section. If they have, they cannot be mutually recursive (reason:
what should be the order of initialization?)
|
|
|
Initialization and finalization of modules
|
|