You can use Units in the same way as in Borland Pascal. However, there are some differences, problems and new features. (Please report the bug if something doesn't work.)
Concerning the syntax of a Unit, you can, if you want, use Extended Pascal syntax to specify a Unit initializer, i.e. instead of writing
begin ... end.
at the end of the Unit, you can get the same result with
to begin do begin ... end (* to begin *);
and there also exists
to end do begin ... end (* to end *);
which specifies a finalization routine. Use this instead of Borland Pascal's exit procedures. You also can specify an order in which initializers are run--see See section GNU Pascal extensions and See section About Pascal and Extended Pascal languages for more about this. There you can also find information about Extended Pascal Modules, an alternative to Units.
At the moment, there are no qualified identifiers, so take care about name clashes between different Units.
When GPC compiles a Unit, it produces two files: an .o
object
file (compatible with other GNU compilers such as GNU C) plus a
precompiled Interface which resides in a .gpi
file.
(See See section GPI files -- GNU Pascal Interfaces for GPI file internals.)
GPC does not automatically recognize that something is a Unit and cannot be linked; you have to tell this by a command line switch:
-c only compile, don't link.
For example, to compile two units, use:
gpc -c myunit1.pas myunit2.pas
Of course, one of the purposes of writing Units is to compile
them separately. However, GNU Pascal allows you to have one or
more Units in the same source file (producing only one .o
file
but separate .gpi
files). You even can have a Program and Units
in one and the same source file; in this case, no .o
file is
produced at all.
You can use the above as a workaround (*$include the Unit *) in case something goes wrong with the .gpi mechanism. (It is a new feature in GPC 2.0 and may be unstable.)
When you have all Units compiled and want to compile the
Program, specify the .o
files in the command line:
gpc hallo.pas myunit1.o myunit2.o
You also can specify the program and the units in one command line:
gpc hallo.pas myunit1.pas myunit2.pas
As an alternative to manually compiling and specifying object files, you can use GPC's AutoMake feature. (WARNING: This is a new feature in GPC 2.0 and may be unstable!) With an additional command-line argument
gpc --automake hallo.pas
GPC tries to behave like Borland Pascal's make
facility and
automatically recompiles Units the source of which has been
changed. It also works if an included file has been changed.
To pass arguments to the compilation of Units, specify them in a
string surrounded by quotation marks after --automake=
. For
example, if you want to give the --verbose
argument not only at
top level but also for (re)compilation of Units, use:
gpc --verbose --automake="--verbose" hallo.pas
For more information about the AutoMake mechanism, see See section GNU Pascal's AutoMake facility.