This is ../p/doc/info/gpc-hr.info, produced by makeinfo version 4.7
from gpc.texi.

INFO-DIR-SECTION GNU programski alati
START-INFO-DIR-ENTRY
* GPC: (gpc-hr).                GNU Pascal prevodilac (compiler).
END-INFO-DIR-ENTRY
INFO-DIR-SECTION Pojedini alati
START-INFO-DIR-ENTRY
* GPC: (gpc-hr)Pozivanje GPC-a. GNU Pascal prevodilac (compiler).
END-INFO-DIR-ENTRY

   Ova datoteka dokumentira GPC prevodilac (engl. compiler).

   Permission is granted to make and distribute verbatim copies of this
manual provided the copyright notice and this permission notice are
preserved on all copies.

   Copyright (C) 1988-2005 Free Software Foundation, Inc.

   Permission is granted to copy and distribute modified versions of
this manual under the conditions for verbatim copying, provided also
that the sections entitled "GNU General Public License", "The GNU
Project", "The GNU Manifesto" and "Funding for free Software" are
included exactly as in the original, and provided that the entire
resulting derived work is distributed under the terms of a permission
notice identical to this one.

   Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for modified
versions, except that the sections entitled "GNU General Public
License", "The GNU Project", "The GNU Manifesto" and "Funding for Free
Software" and this permission notice, may be included in translations
approved by the Free Software Foundation instead of in the original
English.


File: gpc-hr.info,  Node: Top,  Next: Dobrodošli,  Up: (dir)

GNU Pascal
**********

Ovaj priručnik dokumentira kako se pokreće, instalira i održava GNU
Pascal Compiler (GPC), kao i njegove nove značajke i eventualne
nekompatibilnosti, te kako prijavljivati bugove.  Odgovara GPC-u
20050331 (GCC 2.8.1, 2.95.x, 3.2.x, 3.3.x or 3.4.x).

* Menu:

Uvod:

* Dobrodošli::        Dobrodošli na GNU Pascal ...
* Naglasci::          Neke od GPC-ovih interesantnih značajki.
* News::              Novosti - Nova svojstva GNU Pascala (engleski).
* FAQ::               Lista često postavljanih pitanja o GNU Pascalu.

Instalacija:

* Installation::      Instalacija - kako obaviti download, prevesti i
                      instalirati GNU Pascal (engleski).

Korištenje GNU Pascala:

* Invoking GPC::      Pozivanje GPC-a (opcije komandne linije podržane od GNU
                      Pascala).
* Programming::       Programerov vodič u GPC (engleski).
* Borland Pascal::    Brzi vodič za prelaz sa Borland Pascala na GNU Pascal.
* Reference::         Abecedni GPC jezični referentni priručnik (engleski).
* Keywords::          Pascalove ključne riječi i operatori podržani u GPC-u.
* Support::           Gdje dobiti podršku za GNU Pascal; kako prijaviti bug.

Razvoj:

* To Do::             GNU Pascalova "za napraviti" lista (engleski).
* Internals::         Interne strukture - kako dobiti više informacija o samom
                      GPC-ovom kodu (engleski).

Licence:

* Copying::           Kopiranje -- GNU General Public License -- licenca,
                      vaša prava i obaveze kad koristite GPC (engl.).
* Library Copying::   Kopiranje biblioteka -- GNU Lesser General Public
                      License -- licenca, vaša prava i obaveze kod
                      korištenja pojedinih biblioteka (engl.).
* Demo Copying::      GPL uz iznimku -- vaša prava i obaveze kod korištenja
                      ili modifikacije demo programa.

Dodatak:

* Acknowledgments::   Suradnici na GNU Pascal projektu.
* Resursi::           resursi za korištenje s GPC-om.
* GNU::               GNU projekt.
* Indeks::            Indeks koncepta i imena simbola (nedovršeno).

(Napomena: naslovi nekih poglavlja nisu prevedeni zbog unakrsnih referenci iz
           neprevedenih poglavlja priručnika i prema njima. Ponegdje u
           izborniku bi se mogao pojaviti problem oko `č' i sl. zbog buga
           u starijim verzijama - <= 4.0f - GNU `info' programa.)


File: gpc-hr.info,  Node: Dobrodošli,  Next: Naglasci,  Prev: Top,  Up: Top

Dobrodošli na GNU Pascal ...
****************************

...  slobodni 32/64-bitni Pascal prevodilac (engl. compiler) iz
kolekcije GNU prevodilaca (GNU CC ili GCC), koji kombinira Pascal
"front-end" s dokazanim GCC "back-end"-om za generiranje koda i
optimizaciju. Osim njega kolekcija trenutno uključuje prevodioce za
Adu, C, C++, Objective C, Chill, FORTRAN, i Javu.  Za razliku od
konvertera koda kao što je p2c, ovo je istinski prevodilac, ne samo
konverter (u drugi jezik, najčešće C).

   Ova verzija GPC-a odgovara GCC verziji 2.8.1, 2.95.x, 3.2.x, 3.3.x
or 3.4.x.

   Svrha GNU Pascal projekta je da proizvede jedan Pascal prevodilac
(zvan GNU Pascal ili GPC) koji

   * kombinira jasnoću Pascala s moćnim alatima pogodnim za
     programiranje iz realnog života,

   * podržava jednako Pascal standard i Extended Pascal standard
     standard kao definiran od ISO, ANSI i IEEE (ISO 7185:1990, ISO/IEC
     10206:1991, ANSI/IEEE 770X3.160-1989),

   * podržava druge Pascal standarde (UCSD Pascal, Borland Pascal,
     dijelove Borland Delphija i Pascal-SC) toliko dok to služi jasnoći
     i korisnosti,

   * može biti distribuiran pod GNU licencnim uvjetima, i

   * može generirati kod i izvršavati se na svakom računalu za koje GNU
     C prevodilac može generirati kod i vrtiti se na njemu.

   Pascal je originalno dizajniran za učenje. GNU Pascal donosi pogodan
način da se prijeđe na izazovne programerske zadatke bez učenja potpuno
novog jezika.

   Trenutno izdanje implementira Standard Pascal (ISO 7185, razine 0 i
1), većinu Extended Pascala (ISO 10206, težeći potpunom ispunjavanju
standarda), visoko je kompatibilan sa Borland Pascalom (verzija 7.0),
te ima neka pogodnosti za kompatibilnost sa drugim prevodiocima (kao
što je VAX Pascal, Sun Pascal, Mac Pascal, Borland Delphi i Pascal-SC).

   Trenutno izdanje također pruža mnogo korisnih GNU ekstenzija koje se
ne nalaze u ostalim Pascal prevodiocima, npr. da se olakša povezivanje
sa sučeljima u C i drugim jezicima na prenosiv način, zatim da se radi
sa datotekama, direktorijima, datumima i još toga, uglavnom bez
ovisnosti o operacijskom sustavu u podlozi.

   Uključene jedinice pružaju podršku za regularne izraze, cjelobrojnu
aritmetiku, racionalne i realne brojeve neograničene veličine, za
internacionalizaciju, za međuprocesnu komunikaciju, sa tzv.
message-digest i još mnoge dodatne značajke prevodioca.

   Ovaj priručnik sadrži

   * pregled nekih od GPC-ovih najinteresantnijih svojstava, vidi *Note
     Naglasci::,

   * listu novih svojstava od zadnjeg izdanja, vidi *Note News::,

   * GNU Pascal često postavljana pitanja, vidi *Note FAQ::,

   * instrukcije za instaliranje, vidi *Note Installation::,

   * QuickStart Guide - brzi vodič za programere vične Turbo
     Pascal/Borland Pascal prevodiocima, vidi *Note Borland Pascal::,

   * listu opcija komandne linije za pozivanje prevodioca, vidi
     "Pozivanje GPC-a" (*Note Invoking GPC::),

   * Programerski vodič u GPC, koji opisuje Pascal programski jezik
     općenito i GPC specifične aspekte. Vidi *Note Programming::,

   * abecednu referencu GPC jezika, vidi *Note Reference::,

   * listu ključnih riječi i operatora podržanih od GNU Pascala, vidi
     Ključne riječi *Note Keywords::,

   * informacije o tome kako prijavljivati bugove u GNU Pascalu i kako
     dobiti podršku, vidi *Note Support::,

   * listu poznatih bugova i stvari za napraviti, također listu
     ispravljenih bugova i nedavno implementiranih svojstava, see *Note
     To Do::,

   * neke informacije za one koji su zainteresirani kako GNU Pascal
     radi iznutra, see *Note Internals::,

   * listu ljudi koji su doprinijeli koja kaže tko je razvijao i tko
     održava GNU Pascal, vidi *Note Acknowledgments::,

   * GNU General Public License - GNU Opću javnu licencu, koja vas
     informira o vašim pravima i odgovornostima za korištenja,
     modificiranja i distribucije GNU Pascala, vidi *Note Copying::,

   * ostale tekstove o Free Softwareu i GNU Projektu kojima se
     namjeravalo odgovoriti na pitanja kao "što je GNU?" koja bi sada
     mogli imati u umu, vidi *Note GNU::.

   Ako ste upoznati s programiranjem u Standard Pascalu (ISO 7185),
vjerojatno ćete moći jednostavno početi i prevesti svoje programe.
Također, većina ISO Extended Pascal standarda (ISO 10206) je ugrađena u
GNU Pascal. Extended Pascal svojstva koja još uvijek nedostaju iz GPC-a
su `qualified' module import, `protected' module export, skupovni
tipovi s promjenljivim granicama, inicijalizatori strukturiranih
vrijednosti (engl. structured value initializers) i izrazi kao donje
granice raspona (engl. subrange lower bounds).

   Ako ste Borland Pascal programer, vjerojatno biste trebali početi
čitati QuickStart vodič od BP do GNU Pascala, vidi *Note Borland
Pascal::. Ako ste radoznali o novim mogućnostima koje GPC nudi, možete
dobiti ideju iz pregleda GPC naglasaka (*note Naglasci::), i čitati
više detalja o njima u Programmer's Guide to GPC (*note Programming::)
i u abecednom GPC referentnom priručniku (*note Reference::).

   I, molimo vas, razmislite također kako biste doprinijeli GNU Pascal
projektu. Molimo podržite naš rad doprinoseći GNU Pascalu programskim
primjerima, prijavama bugova, dokumentiranjem, ali čak i vlastitim
poboljšanjima prevodioca.

   Sva registrirana imena korištena u ovom priručniku pripadaju njihovim
respektivnim vlasnicima.


File: gpc-hr.info,  Node: Naglasci,  Next: News,  Prev: Dobrodošli,  Up: Top

1 Neke od najinteresantnijih značajki GPC-a
*******************************************

GNU Pascal prevodilac (GPC) je, kao što ime govori, Pascal prevodilac
(engl.  compiler) iz GNU obitelji (`http://www.gnu.org/software/gcc/').
Ovo znači:

   * GPC je 32/64-bitni prevodilac,

   * nema ograničenja kao što je 64 kB ili 640 kB limit poznat iz nekih
     operacijskih sustava - čak i na tim sustavima -,

   * radi na svim operacijskim sustavima podržanim od GNU C prevodioca,
     uključujući

        - Linux (http://www.linux.org) na Intelu, Alphi, S390, i na svim
          ostalim podržanim tipovima hardvera,

        - BSD obitelj: FreeBSD (http://www.freebsd.org), NetBSD
          (http://www.netbsd.org), OpenBSD (http://www.openbsd.org),

        - DOS sa 32 bita, koristeći DJGPP
          (http://www.delorie.com/djgpp/) ili EMX,

        - MS-Windows 9x/NT, koristeći Cygwin (http://cygwin.com) ili
          mingw (http://www.mingw.org) ili MSYS
          (http://www.mingw.org/msys.shtml),

        - OS/2 sa EMX,

        - Mac OS X,

        - MIPS-SGI-IRIX,

        - Alpha-DEC-OSF,

        - Sparc-Sun-Solaris,

        - HP/UX,

     i druge (zabilješka: runtime sistem podržava samo ASCII bazirane
     sisteme; to uključuje gotovo sve današnje sustave, međutim
     nekoliko IBM strojeva još uvijek koristi EBCDIC; na tima,
     prevodilac bi se mogao izvršavati, ali bi runtime podrška trebala
     velike izmjene),

   * može služiti kao nativni prevodilac ili prevodilac između sistema
     (engl. cross-compiler) - između svih podržanih sistema,

   * proizvodi visoko optimirani kod za sve te sisteme,

   * slobodan je softver Free Software
     (http://www.gnu.org/philosophy/free-sw.html) (Open-Source Software
     (http://www.opensource.org)) u skladu sa *GNU General Public
     License* (http://www.gnu.org/copyleft/gpl.html) licencom),

   * kompatibilan je sa ostalim GNU jezicima i alatima kao što su GNU C
     i GNU debugger (ili, ako više volite, program za simboličko
     ispravljanje pogrešaka u ispravljanom programu).


   Prevodilac podržava slijedeće jezične standarde i kvazi-standarde:

   * ISO 7185 Pascal (*note Resursi::),

   * većinu dijelova ISO 10206 Extended Pascala,

   * Borland Pascal 7.0,

   * dijelove Borland Delphi, Mac Pascala i Pascal-SC (PXSC).

   Neki naglasci:

   * Iz Standard Pascala: Mnogi popularni Pascal prevodioci tvrde da
     proširuju Standard Pascal, ali im nedostaju ove važne značajke.

        - Polja kao konformni parametri - standardni i komforan način
          prosljeđivanja polja (ARRAY) varijabilne veličine procedurama
          i funkcijama.  [Example (conformantdemo.pas)]

        - Prosljeđivanje lokalnih procedura kao proceduralnih
          parametara - s punim pristupom svim varijablama "nadređene"
          procedure.  [Example (iteratordemo.pas)]

        - Automatski datotečni međuspremnici (engl. file buffers) i
          standardne `Get' i `Put' procedure. Predviđajuće čitanje
          (engl. read-ahead) bez privremenih varijabli. [Example
          (filebuf1demo.pas)] Ovo dozvoljava, na primjer, da se
          provjeri ulaz iz tekst datoteka prije čitanja bez konverzije
          kroz znakovne nizove (engl. strings). [Example
          (filebuf2demo.pas)]

        - Istinski pakirani zapisi (RECORD) i polja. Pakira 8 Booleovih
          varijabli u jedan bajt.  [Example (packdemo.pas)]

        - Interne datoteke. Ne morate se brinuti o kreiranju
          privremenih imena datoteka i njihovom brisanju kasnije.
          [Example (intfiledemo.pas)]

        - Globalni `goto'. (Da, `goto' ima svoju ulogu kada nije
          ograničen na trenutni potprogram.) [Example (parserdemo.pas)]

        - Automatski postavlja diskriminantu varijabilnog zapisa
          (RECORD) u `New'.  [Example (variantdemo.pas)]

        - Skupovi (SET) proizvoljne veličine. [Example
          (bigsetsdemo.pas)]

   * Iz Extended Pascala:

        - Znakovni nizovi (strings) proizvoljne duljine.  [Example
          (stringschemademo.pas)]

        - `ReadStr' i `WriteStr'. Čitajte iz i pišite u znakovne nizove
          sa punim komforom `ReadLn'/`WriteLn'.  [Example
          (rwstringdemo.pas)]

        - Rutine za predstavljanje datuma i vremena neovisne od sistema
          (prenosive).  [Example (datetimedemo.pas)]

        - Iteracija pomoću članova skupa:
          `for Ch in ['A' .. 'Z', 'a' .. 'z'] do ...' [Example
          (bigsetsdemo.pas)]

        - Proširene operacije nad skupovima (simetrična diferencija,
          `Card')

        - Generalizirane `Succ' i `Pred' funkcije
          (`foo := Succ (bar, 5);').

        - Kompleksni brojevi. [Example (mandelbrot.pas)] [Example
          (parserdemo.pas)]

        - Operatori za potenciranje (`pow' i `**') za realne i
          kompleksne brojeve.

        - Inicijalizirane varijable. [Example (initvardemo.pas)]

        - Funkcije mogu vraćati vrijednost tipa zapis ili polje
          (Record, Array).

        - Varijable za imenovanu povratnu vrijednost u funkcijama.
          [Example (resultvardemo.pas)]

        - Moduli.

        - Ne-dekadski brojevi u bazama od 2 do 36: `baza#broj'.

        - `MinReal', `MaxReal', `EpsReal', `MaxChar' konstante.

        - Schemata - Pascalov način da se dobiju dinamička polja bez
          nestašnih trikova [Example (schemademo.pas)]

        - Lokalne varijable mogu imati dinamičku veličinu.  [Example
          (dynamicarraydemo.pas)]

        - Pristup odsječcima polja - pristupa se dijelovima polja kao
          manjem polju, čak i na lijevoj strani operacije dodjele
          vrijednosti (engl. assignment) [Example (arrayslicedemo.pas)]

   * Kompatibilan sa Borland Pascalom 7.0 s objektima (BP):

        - Podržava jedinice (UNIT), objekte, ..., i čini čak i stvari
          kao `absolute' varijable prenosivima. [Example (absdemo.pas)]

        - Dolazi s prenosivim verzijama standardnih BP jedinica sa punim
          izvornim kodom.

        - Istinski mrežno-transparentna CRT jedinica: možete izvršavati
          svoje CRT aplikacije lokalno ili dok ste prijavljeni udaljeno
          (remote login), bez potrebe za brigom o različitim tipovima
          terminala. Kompatibilna s BP jedinicom, ali s mnogim
          proširenjima, kao npr. preklapajući prozori.  [Example
          (crtdemo.pas)]

        - Potpuno funkcionalna GUI (X11) verzija CRT (također potpuno
          mrežno transparentna).

        - `Random' funkcija koja može proizvesti iste sekvence
          pseudo-slučajnih brojeva kao i ona u BP - ako vam je to
          potrebno umjesto mnogo jače elaboriranog inicijalnog
          algoritma.

        - Podržava proceduralne varijable u stilu BP-a, jednako kao i
          procedure kao parametre iz Standard Pascala. [Example
          (procvardemo.pas)]

        - `Ports' jedinica dozvoljava pristup I/O portovima na
          sistemima gdje to ima smisla. [Example (portdemo.pas)]

        - Specijalne kompatibilnostne značajke za pomoć u migraciji s
          BP-a na GPC, kao `GPC for BP' jedinica koja pruža neke od
          GPC-ovih značajki za BP, te neke rutine za pristup skupovima
          velikih memorijskih blokova na uniforman način pod GPC-om i
          BP-om (čak i u tzv. realnom modu).  [Example (bigmemdemo.pas)]

        - Dolazi sa BP-kompatibilnom `binobj' uslugom.  [Example
          (binobjdemo.pas)]

   * Iz Borland Delphija:

        - `abstract' tipovi objekata i metoda

        - `is' i `as' operatori za testiranje pripadnosti objekta tipu

        - komentari s `//'

        - `Setlength' procedura za znakovne nizove (string) čini
          nepotrebnim korištenje trikova kao što je pridodjeljivanje
          "nultom karakteru".

        - `Initialize' i `Finalize' za rukovanje varijablama na niskoj
          razini.

   * Iz Pascal-SC (PXSC):

        - Korisnički redefinirani (preopterećeni) operatori. Zbrajajte
          svoje vektore sa `+'.

   * Pažljivo definirana GNU proširenja pomažu vam da učinite svoje
     programe iz realnog života prenosivima:

        - 64-bitni cjelobrojni tipovi sa i bez predznaka.

        - Specijalni tipovi garantiraju kompatibilnost sa drugim GNU
          jezicima kao što je GNU C. Direktive kao `{$L foo.c}' čine
          jednostavnim održavanje projekata pisanih u više jezika, npr.
          uključivanje koda pisanog u drugim jezicima u Pascal programe
          [Primjer (Pascal dio) (c_gpc.pas)] [Primjer (C dio)
          (c_gpc_c.c)],

        - ili uključivanje Pascal koda u programe pisane u drugim
          jezicima.  [Primjer (Pascal dio) (gpc_c_pas.pas)] [Primjer
          (Pascal jedinica) (gpc_c_unit.pas)] [Primjer (C dio)
          (gpc_c_c.c)]

        - Proširenja kao `BitSizeOf' i `ConvertFromBigEndian' pomažu
          rješavanju problema s različitim tipovima i unutrašnjim
          poretkom (engl. endianess - big endian, little endian).
          [Example (endiandemo.pas)]

        - Male sitnice kao što su `DirSeparator', `PathSeparator',
          `GetTempDirectory' pomažu vam da pišete programe koji
          izgledaju i osjećaju se "kod kuće" na svim operativnim
          sistemima.

        - `PExecute' rutina dozvoljava izvođenje 'child' procesa na
          prenosiv način koji u potpunosti iskorištava višezadaćne
          (engl. multitasking) okoline.  [Example (pexecutedemo.pas)]

        - GNU GetOpt rutine daju komforan pristup kratkim i dugim
          opcijama u komandnoj liniji u Unix-stilu sa i bez argumenata.
          [Example (getoptdemo.pas)]

        - Rutine kao `FSplit' ili `FSearch' ili `FExpand' znaju o
          specifičnostima raznih operativnih sistema.  [Example
          (fexpanddemo.pas)]

        - `FormatTime' funkcija pušta vas da formatirate vrijednosti
          datuma i vremena, prema raznim pravilima formatiranja.
          [Example (formattimedemo.pas)]

   * Korisne i prenosive GNU standardne jedinice:

        - `Pipes' jedinica daje međuprocesnu komunikaciju čak i pod
          običnim DOS-om. [Example (pipedemo.pas)] [Demo proces za
          primjer (demoproc.pas)]

        - GNU multipreciznostna `GMP' jedinica omogućava aritmetiku
          cijelih, realnih i racionalnih brojeva proizvoljne
          preciznosti.  [Primjer: faktorijele (factorial.pas)]
          [Primjer: Fibonaccijev niz (fibonacci.pas)] [Primjer:
          potenciranje (power.pas)] [Primjer: potenciranje realnih
          brojeva (realpower.pas)] [Primjer: pi (pi.pas)]

        - POSIX funkcije poput `ReadDir', `StatFS' ili `FileLock'
          pružaju efikasno, lako za korištenje i prenosivo sučelje
          (engl. interface) prema operacijskom sustavu. [Example
          (readdirdemo.pas)] [Example (statfsdemo.pas)], [Example
          (filelockdemo.pas)]

        - `DosUnix' jedinica kompenzira neke nekompatibilnosti između
          dviju obitelji operacijskih sustava.  [Example
          (dosunixdemo.pas)]

        - `MD5' jedinica izračunava MD5 sume poruka (engl. message
          digest), u skladu s RFC 1321. [Example (md5demo.pas)]

        - `FileUtils' jedinica pruža neke rutine za rukovanje
          datotekama i direktorijima na višoj razini.  [Example
          (findfilesdemo.pas)]

        - `StringUtils' jedinica pruža neke rutine za rad sa znakovnim
          nizovima na višoj razini. [Example (stringhashdemo.pas)]

        - `Intl' jedinica za internacionalizaciju.  [Example
          (gettextdemo.pas)] [Example (localedemo.pas)]

        - `Trap' jedinica za hvatanje grešaka u vremenu izvođenja
          (runtime-errors) i njihovo obrađivanje unutar programa.
          [Example (trapdemo.pas)]

        -  A `TFDD' jedinica koja omogućuje neke trikove s tekst
          datotekama, npr. "tee" datoteku koja prouzročuje da se sve
          pisano u nju ispisuje u dvije druge datoteke. [Example
          (tfdddemo.pas)]

        - `HeapMon' jedinica koja pomaže detektirati "curenje" memorije
          (engl. memory leaks) u vašim programima.

   Demo programi spomenuti gore su raspoloživi na WWW-u jednako kao i u
GPC distribucijama, binarnim i source.

   Nedostaci:

   * GNU simbolički debugger (GDB) još ne razumije Pascal sintaksu i
     tipove; potrebno je koristiti C sintaksu kod ispravljanja programa
     GDB-om.

   * Sa GPC-om prevođenje traje dulje nego s npr. Borland Pascalom.

   *Suradnici dobrodošli!*

   Sposobni, predani programeri su uvijek dobrodošli u GNU Pascal tim.
Ako želite biti nezavisni od kompanija kojima morate plaćati za
prevodilac sa mnogo restriktivnijim uvjetima licenciranja koji se
izvršava na _jednom_ operacijskom sustavu, budite pozvani da se
pridružite razvojnom timu, *Note Acknowledgments::.


File: gpc-hr.info,  Node: News,  Next: FAQ,  Prev: Naglasci,  Up: Top

2 New Features of GNU Pascal.
*****************************

   GPC's new or changed features since the last (non alpha/beta) GPC
release are listed here. Items without further description refer to new
routines, variables or options.

   Features implemented for compatibility to other compilers are marked
with, e.g., `(B)' for BP compatibility.

   A few old and obsolete features have been dropped or replaced by
cleaner, more flexible or otherwise more useful ones. This might lead
to minor problems with old code, but we suppose they're rare and easy
to overcome. Backward-incompatible changes are marked with `(@)'.

   * new options `--[no]-nonlocal-exit' (default in `--ucsd-pascal' and
     `--mac-pascal') (fjf988[fijk].pas, fjf1062*.pas) (U) (M)

   * new options `--[no]-object-checking' (on by default) to check on
     virtual method calls if VMT pointer is not nil and has matchin
     `Size' and `NegatedSize' entries, new options
     `--[no]-range-and-object-checking' which are now equivalent to
     `$R[+-]' (fjf1053*.pas) (B)

   * new options `--[no]-pointer-checking',
     `--[no]-pointer-checking-user-defined'; new variable
     `ValidatePointerPtr' (fjf1052*.pas, pcerrorc.pas) (these options
     are _off_ by default!)

   * new options `--[no]-implicit-result' (fjf1022*.pas) (on by default
     *only* in `--delphi' mode!) (D) (@)

   * new options `--{en,dis}able-predefined-identifier' (fjf1037*.pas)

   * `import' within a routine (mod15[c-e].pas)

   * the option `--no-debug-info' was renamed to
     `--disable-debug-info', and `--no-default-paths' was renamed to
     `--disable-default-paths' (@)

   * qualified identifiers (chief18.pas, fjf260*.pas, fjf921*.pas,
     grp1.pas, kurzw1.pas, mod{9,10,13..17}*.pas) (@)

   * with `-Wnested-comments' and without `--nested-comments' warn
     about comment openers found within comments (fjf1017*.pas)

   * new options `--[no-]case-value-checking' (fjf1012*.pas)

   * optimize arithmetic with a complex and a real operand
     <20020118143553.B28837@artax.karlin.mff.cuni.cz>

   * range checking
     <Pine.LNX.4.21.0012091605570.8168-100000@rusty.russwhit.com>
     (chuck5.pas, fjf446.pas, fjf989*.pas, fjf992*.pas,
     fsc{01..37}*.pas, miklos1[bc].pas,
     mir{016,021..028,030..047}*.pas, ole[12]*.pas, russ4*.pas)

   * `Exit' with an argument (non-local exits not yet supported)
     (fjf988*.pas) (U) (M)

   * new options `--[no-]propagate-units' (on by default with
     `--mac-pascal', off in other dialects) (fjf987*.pas) (M); this
     also covers the item "unit inheritance"

   * enable `Pointer' in `--mac-pascal' mode (Mac Pascal has a
     `Pointer' function which does the same as a type-cast to
     `Pointer'; though adding `Pointer' as a type allows more, it's
     backward-compatible) (M)

   * `&' and `|' (shortcut `and' and `or') (fjf981*.pas) (M)

   * `Leave' and `Cycle' (equivalent to `Break' and `Continue')
     (avo3.pas) (M)

   * optimize `WriteLn (... STRING_CONSTANT)' and `Write (...
     STRING_CONSTANT, STRING_CONSTANT ...)'

   * `BindingType' is now a packed record as EP demands (fjf975a.pas)
     (E)

   * EP structured initializers (fjf964*.pas, fjf967*.pas, fjf968*.pas)
     (E)

   * EP record, array, set values (constdef.pas, fjf966*.pas,
     fjf971*.pas) (E)

   * `gp': `PC' now sets the compiler for both Pascal and C unless `CC'
     is set explicitly

   * `Discard'

   * `Integer', `Word', `Cardinal' are now equivalent to `PtrInt',
     `PtrWord', `PtrCard', no more (necessarily) to C's `int' and
     `unsigned int' (@)

   * new types `CInteger', `CWord', `CCardinal'

   * new make variable `GPC_PAGESIZE' to set the page size when
     building the manual (PDF, PostScript, DVI)

   * `qualified' and import lists are no more allowed after `uses'
     (only after `import', as EP demands) (@)

   * the `GMP' unit doesn't support gmp-2.x anymore (if you used it,
     just upgrade to a newer GMP version) (@)

   * conflicts between object fields/methods and ancestor type names
     are detected as required by OOE (fjf945*.pas) (@) (O)

   * repeated function headings (in `forward' declarations and
     interfaces) are checked stricter: if one has a result variable, so
     must the other (according to the OOE draft) (@) (O)

   * the `Pipe' unit was renamed to `Pipes' because of a name conflict
     (@)

   * empty parameter lists can be written as `()' (chief54*.pas,
     delphi6*.pas) (D)

   * GMP unit: `mpf_sin', `mpf_cos'

   * the test suite output is now by default stored in DejaGnu
     compatible files `gpc.log' and `gpc.sum' in the `p/test/'
     directory; other available test targets are `pascal.check-short'
     and `pascal.check-long' (@)

   * new options `-W[no-]dynamic-arrays' (fjf931*.pas)

   * new argument to `_p_initialize' (@)

   * `UMask'

   * new option `--no-debug-source'

   * new lexer (no directly user-visible difference, but should allow
     for better handling of lexer-based problems in the future)

   * `CompilerAssert' (fjf904*.pas)

   * options `--[no]-assert' renamed to `--[no]-assertions' (necessary
     to avoid a conflict with GCC) (@)

   * new options `--[no-]range-checking', also as short compiler
     directives `{$R+}'/`{$R-}' (default is on) (C, E, B, @)

   * new options `--[no-]methods-always-virtual' (fjf903*.pas) (M)

   * new options `--[no-]pointer-arithmetic',
     `--[no-]cstrings-as-strings', `-W[no-]absolute' (all of which
     `--[no-]extended-syntax' implies)

   * `Integer2StringBase', `Integer2StringBaseExt'

   * new constants `NumericBaseDigits', `NumericBaseDigitsUpper'

   * allow assigning, passing by value and returning objects, with
     assignments of an object of derived type to one of a base type
     (chief35[ab].pas, fjf451*.pas, fjf696[ef].pas, fjf884*.pas), BP
     compatible except for a bug in the BP feature itself (see the
     comment in `p/test/fjf451h.pas') (B)

   * new options `-W[no-]object-assignment'

   * warn (except in `--borland-pascal') if a virtual method overrides
     a non-virtual one (chief52*.pas)

   * warn when an non-abstract object type has virtual methods, but no
     constructor (chief51*.pas)

   * `--maximum-field-alignment' does not apply to `packed' records

   * `ArcSin', `ArcCos'

   * trimming string relations as functions (`EQPad' etc.) (fjf873.pas)

   * new options `-W[no-]interface-file-name'

   * `SeekEOF' and `SeekEOLn' use `Input' implicitly when no file is
     given (fjf871.pas) (B)

   * tagging feature for `with' statements (tom6.pas)
     <200012022215.eB2MFD614424@wsinpa16.win.tue.nl> (Sun Pascal)

   * new option `--sun-pascal'

   * field names and array indices in initalizers are recognized
     (waldek5*.pas) (options `-W[no-]field-name-problem' removed, @)

   * object directives `published', `public' (both equivalent),
     `protected' (scope limited to object type and derived object
     types), `private' (scope limited to current unit/module)
     (fjf864*.pas) (options `-W[no-]object-directives' removed, @)

   * the operator precedence and associativity of `+' and `-' is now as
     defined in EP by default (and as in BP with `--borland-pascal')
     <Pine.LNX.4.44.0210251249500.6181-100000@duch.mimuw.edu.pl>
     (fjf863*.pas) (@)

   * `Integer (16)' etc. changed to `Integer attribute (Size = 16)'
     (works for integer and Boolean types) (fjf861.pas) (@)

   * types can have attributes (note: no preceding `;') (fjf860*.pas)

   * dynamic object methods (fjf859.pas) (B)

   * in `--borland-pascal' mode, `Assign' unconditionally
     (re-)initializes its file parameter (fjf858.pas) (B)

   * GPC doesn't use `gpm' files anymore (instead, each module has an
     implicit `MODULENAME-all.gpi' interface which is a regular `gpi'
     file)

   * make the program/module/unit finalizers non-public (`static' in C
     sense), omit them if easily possible

   * new options `-W[no-]parentheses' (fjf848*.pas)

   * non-`interface' modules with empty implementation part (pmod1.pas,
     fjf843.pas)

   * `maximum-field-alignment' and `[no-]field-widths' work as local
     compiler directives now (fjf842.pas)

   * dropped `{$debug-statement}' (should not be necessary anymore, now
     that debug info mostly works)

   * new options `--[no-]longjmp-all-nonlocal-labels'

   * object methods can have attributes (fjf826*.pas)

   * new attributes `iocritical' (fjf824*.pas), `ignorable'
     (fjf839*.pas) for routines

   * dropped computed `goto' (never worked for nonlocal `goto' into the
     main program, implementing it would be quite difficult, probably
     not worth it) (@)

   * new type `AnyFile' for parameters and pointer targets (fjf821*.pas)

   * `TimeStamp' is now a packed record as EP demands (fjf975b.pas) (E)

   * Mac Pascal specific features are supported according to the
     dialect options (M)

   * `--interface-only' does not require `-S' or `-c' anymore (and does
     not create an object file)

   * `initialization', `finalization' (D)

   * `TimeZone' in `TimeStamp' counts seconds _east_ of UTC now (not
     west, as before) (datetimedemo.pas) (@)

   * `export FOO = all (...)' (fjf811*.pas)

   * new options `-W[no-]local-external' (implied by `-Wall')

   * type-casts are BP compatible now, in particular, value type-casts
     between ordinal and real or complex types don't work anymore (B)
     (@)

   * all non-ISO-7185 keywords can be used as identifiers (with two
     small exceptions) (fjf440.pas)

   * `pack-struct' does not imply bit-level packing anymore (only
     explicit `packed' records and arrays do) (@)

   * new options `--[no-]ignore-packed' (`--ignore-packed' is the
     default in BP mode) (fjf796*.pas) (B) (@)

   * new option `--maximum-field-alignment=N'

   * new options `{$[no-]pack-struct}' as a compiler directive

   * `attribute' for routines doesn't imply `forward' anymore (so you
     don't have to declare routines twice in a program or
     implementation part when setting the linker name or some other
     attribute) (@)

   * `static', `volatile' and `register' for variables and `inline' for
     routines are no prefix-directives anymore, but `attribute's (@)

   * combining several dialect options (such as `--extended-pascal
     --borland-pascal') doesn't work anymore (what should this mean,
     anyway? Combine the features, but also the warnings from
     both!?!?!?) (@)

   * `external' without `name' defaults to all-lowercase now (@)

   * `c', `c_language' and `asmname' are deprecated (@)

   * `external name 'foo'' (fjf780.pas), `external 'libname' name
     'foo'' (where `libname' is ignored) (B)

   * Mac Pascal directives `definec', `macro', `undefc', `ifc',
     `ifoptc', `elsec', `elifc', `endc', `errorc' (treated as
     equivalent to the corresponding existing ones) (M)

   * units without `implementation' part (M)

   * new options `--vax-pascal', `--mac-pascal'

   * attributes `const' for variables and `name' for variables,
     routines and modules; assembler names and module/unit file names
     can now be expressions (which must yield string constants)
     (fjf781*.pas, fjf809*.pas)

   * the utilities `gpidump' and `binobj' are installed with GPC (B)

   * new options `-W[no-]identifier-case',
     `-W[no-]identifier-case-local' (fjf751*.pas)

   * new compiler directive `$R foo', equivalent to `$L foo.resource'
     (B)

   * dropped `--[no-]borland-char-constants' (now simply coupled to
     dialect options) (@)

   * test suite: support progress messages (`TEST_RUN_FLAGS=-p' from
     the Makefile; `-p' in testgpc); see
     `http://fjf.gnu.de/misc/progress-messages.tar.gz'

   * `=' and `<>' comparisons of structures (arrays, records, ...)
     except strings and sets are forbidden now (@) (E)

   * irrelevant operands and arguments (e.g.: `foo in []'; `bar * []';
     `Im (baz)' if `baz' is of real type) are not necessarily evaluated
     anymore (which is allowed by the standard); instead, a warning is
     given if they have side-effects (@)

   * accept only one program, unit, module interface or implementation
     or a module interface and the implementation of the same module in
     one file; new options `--[no-]ignore-garbage-after-dot'
     (fjf735*.pas) (@)

   * new options `-W[no-]implicit-io' (fjf734*.pas)

   * new options `--enable-keyword', `--disable-keyword' (fjf733*.pas)

   * `CBoolean' (fjf727.pas)

   * dropped the usage of `GetMem' as a function with one parameter
     (only the BP compatible usage as a procedure with two parameters
     remains) (@)

   * accessing the variable `FileMode' now requires using the `GPC'
     (or, for BP compatibility, the `System') unit (@)

   * `DupHandle'

   * dropped the predefined dialect symbols `__CLASSIC_PASCAL__',
     `__STANDARD_PASCAL__', `__EXTENDED_PASCAL__', `__OBJECT_PASCAL__',
     `__UCSD_PASCAL__', `__BORLAND_PASCAL__', `__DELPHI__',
     `__PASCAL_SC__' and `__GNU_PASCAL__' (one can use `{$ifopt
     borland-pascal}' etc. instead) (@)

   * `Succ', `Pred', `Inc', `Dec' for real numbers (fjf714*.pas)

   * use environment variables `GPC_UNIT_PATH', `GPC_OBJECT_PATH'

   * new options `-W[no-]float-equal'

   * new option `--ucsd-pascal'

   * dropped the syntax `type foo = procedure (Integer, Real)' (i.e.,
     without parameter names) (@)

   * CRT: new argument `On' to `CRTSavePreviousScreen'

   * `SetUserID', `SetGroupID'

   * `HeapChecking'

   * new built-in procedure `Assert'; new options `--[no]-assert' (also
     `{$C+}', `{$C-}' for Delphi compatibility) (fjf665*.pas) (D)

   * `ProcessGroup'

   * StringUtils: `QuoteEnum'

   * `CurrentRoutineName' (fjf752.pas)

   * TFDD: new unit

   * gpc-run: new options `-e FILE' and `-E FILE' (redirect/append
     standard error)

   Have fun,

   The GNU Pascal Development Team


File: gpc-hr.info,  Node: FAQ,  Next: Installation,  Prev: News,  Up: Top

3 Često postavljana pitanja (FAQ) o GNU Pascalu.
************************************************

Izdanje 0.9, kolovoz 2000
-------------------------

   Ovo je lista često postavljanih pitanje (FAQ) za GNU pascal. Ako vam
niti FAQ niti dokumentacija ne pomažu, detektirali ste *bug* u
dokumentaciji koji biste trebali prijaviti, *Note Mailing List::.
Molimo vas da zaista to i učinite, kako bismo mogli poboljšati
dokumentaciju.

* Menu:

* GNU Pascal::               GNU Pascal
* Instaliranje GPC-a::       Instaliranje GPC-a
* GPC na DJGPP-u::           GNU Pascal na DJGPP (MS-DOS) platformi
* Znakovni nizovi u GPC-u::  Znakovni nizovi (strings)
* Traženje pomoći::          Traženje pomoći
* FAQ "Razno"::              Razno


File: gpc-hr.info,  Node: GNU Pascal,  Next: Instaliranje GPC-a,  Up: FAQ

3.1 GNU Pascal
==============

* Menu:

* Što i zašto::                        Što i zašto?
* Trenutna verzija::                   Koja je trenutna verzija?
* Kompatibilnost sa Turbo Pascalom::   Da li je kompatibilan s
                                         Turbo Pascal-om (R)?
* Podržane platforme::                 Na kojim platformama GNU Pascal radi?


File: gpc-hr.info,  Node: Što i zašto,  Next: Trenutna verzija,  Up: GNU Pascal

3.1.1 Što i zašto?
------------------

Svrha GNU Pascal projekta je da proizvede jedan Pascal prevodilac (zvan
GNU Pascal ili GPC) koji

   * kombinira jasnoću Pascala s moćnim alatima pogodnim za
     programiranje iz realnog života,

   * podržava jednako Pascal standard i Extended Pascal standard
     standard kao definiran od ISO, ANSI i IEEE (ISO 7185:1990, ISO/IEC
     10206:1991, ANSI/IEEE 770X3.160-1989),

   * podržava druge Pascal standarde (UCSD Pascal, Borland Pascal,
     dijelove Borland Delphija i Pascal-SC) toliko dok to služi jasnoći
     i korisnosti,

   * može biti distribuiran pod GNU licencnim uvjetima, i

   * može generirati kod i izvršavati se na svakom računalu za koje GNU
     C prevodilac može generirati kod i vrtiti se na njemu.

   Pascal je originalno dizajniran za učenje. GNU Pascal donosi pogodan
način da se prijeđe na izazovne programerske zadatke bez učenja potpuno
novog jezika.

   Trenutno izdanje implementira Standard Pascal (ISO 7185, razine 0 i
1), većinu Extended Pascala (ISO 10206, težeći potpunom ispunjavanju
standarda), visoko je kompatibilan sa Borland Pascalom (verzija 7.0),
te ima neka pogodnosti za kompatibilnost sa drugim prevodiocima (kao
što je VAX Pascal, Sun Pascal, Mac Pascal, Borland Delphi i Pascal-SC).

   Trenutno izdanje također pruža mnogo korisnih GNU ekstenzija koje se
ne nalaze u ostalim Pascal prevodiocima, npr. da se olakša povezivanje
sa sučeljima u C i drugim jezicima na prenosiv način, zatim da se radi
sa datotekama, direktorijima, datumima i još toga, uglavnom bez
ovisnosti o operacijskom sustavu u podlozi.

   Uključene jedinice pružaju podršku za regularne izraze, cjelobrojnu
aritmetiku, racionalne i realne brojeve neograničene veličine, za
internacionalizaciju, za međuprocesnu komunikaciju, sa tzv.
message-digest i još mnoge dodatne značajke prevodioca.


File: gpc-hr.info,  Node: Trenutna verzija,  Next: Kompatibilnost sa Turbo Pascalom,  Prev: Što i zašto,  Up: GNU Pascal

3.1.2 Koja je trenutna verzija?
-------------------------------

Prije srpnja 2000 release verzije su obično slijedile nekoliko mjeseci
jedna drugu. Od tada se nova verzija pojavila gotovo svakih nekoliko
dana, dostupna kao source arhiva s GPC web sitea,
`http://www.gnu-pascal.de'.

   Za detalje od novim mogućnostima, pogledajte sekciju `News' na web
siteu. O bug-ovima koji su nedavno popravljeni, molimo pogledajte
`Done' sekciju na To-Do ("preostalo za napraviti") listi.

   GPC koristi GCC kao "back-end", što znači da koristi dokazano GCC-ovo
sučelje za generiranje strojnog izvršnog koda, nakon što je "front-end"
"prožvakao" ulaznu sintaksu Pascal jezika. U distribuciji su priložene
zakrpe za GCC 2.8.1 i GCC 2.95.x, ali se preporučuje da koristite GCC
2.95.x.


File: gpc-hr.info,  Node: Kompatibilnost sa Turbo Pascalom,  Next: Podržane platforme,  Prev: Trenutna verzija,  Up: GNU Pascal

3.1.3 Da li je kompatibilan s Turbo Pascalom (R)?
-------------------------------------------------

GPC nije usputni nadomjestak za Borlandov Turbo Pascal (R).  Gotovo sve
jezične mogućnosti BP-a su podržane. Primjetne iznimke su formati
znakovnih nizova (kao što je diskutirano niže u dokumentu), ili `Mem' i
`Port' pseudo-polja, iako zamjena za potonje na IA32 platformi postoji
u `Ports' jedinici.

   Gotovo sve mogućnosti BP-ove runtime biblioteke su podržane u GPC-u,
bilo ugrađenim mogućnostima prevodioca ili jedinicama sa istim imenima
kao i korespondentne BP jedinice.

   Za detalje o kompatibilnosti, o nekoliko preostalih nekompatibilnosti
i nekim korisnim alternativama za mogućnosti BP-a, pogledajte `Borland
Pascal' poglavlje u GPC priručniku.  (*note Borland Pascal::)


File: gpc-hr.info,  Node: Podržane platforme,  Prev: Kompatibilnost sa Turbo Pascalom,  Up: GNU Pascal

3.1.4 Na kojim platformama GNU Pascal radi?
-------------------------------------------

GPC koristi GCC "backend", tako da bi trebao raditi na svim sustavima
podržanim od GNU CC-a. Ovo uključuje širok raspon Unix sustava, MS-DOS,
OS/2 i Win32. Puna lista platformi podržanih od GCC-a može se naći u
datoteci `INSTALL' GCC distribucije. Sve te platforme nisu zapravo
testirane, ali je poznato da radi na slijedećim platformama:

ix86-linux                    (Linux 2.x, ELF)
i486-linuxaout                
i486-linuxoldld               
i386-freebsd1.2.0             
AIX 4.2.1                     
AIX 4.3                       
DJGPP V2                      (Dos)
EMX 0.9B                      (OS/2, Dos)
Cygwin32 beta20 i više        (MS-Windows95/98, MS-Windows NT)
mingw32                       (MS-Windows95/98, MS-Windows NT)
MSYS                          (MS-Windows)
mips-sgi-irix5.3              
mips-sgi-irix6.5              
sun-sparc-sunos4.1.4          
sparc-sun-solaris2.x          
sun-sparc-solaris 2.5.1       
sun-sparc-solaris 2.6         
sun-sparc-solaris 7           
sun-sparc-solaris 8           
alpha-unknown-linux           
alpha-dec-osf4.0b             
s390-ibm-linux-gnu            

   *OK narode - šaljite nam svoje pripovjesti o uspjehu, s kanoničkim
imenima mašina!*


File: gpc-hr.info,  Node: Instaliranje GPC-a,  Next: GPC na DJGPP-u,  Prev: GNU Pascal,  Up: FAQ

3.2 Instaliranje GPC-a
======================

Najsvježije instrukcije za instalaciju možete naći u GPC priručniku ili
u datoteci `INSTALL' u source distribucijama, ili na GPC web
poslužitelju.  (*note Installation::)

   Slijedeća poglavlja opisuju što biste mogli trebati ili željeti osim
samog GPC-a.

* Menu:

* Dokumentacijske datoteke::  Što slijedeće čitati?
* Komponente::                Koje komponente trebam za prevođenje Pascal koda?
* Debugger::                  Kako da ispravljam moje Pascal programe?
* Libraries::                 Biblioteke - koje bih dodatne biblioteke trebao
                                imati?
* Darovane jedinice::         Darovane jedinice
* IDE::                       Možete li preporučiti integriranu razvojnu
                                okolinu (IDE)?


File: gpc-hr.info,  Node: Dokumentacijske datoteke,  Next: Komponente,  Up: Instaliranje GPC-a

3.2.1 Što slijedeće čitati?
---------------------------

Nakon instaliranja GPC-a, molimo provjerite datoteke u direktoriju
`/usr/local/doc/gpc':

`README'           Opće informacije o GPC-u
`FAQ'              Ovaj FAQ :-)
`NEWS'             Promjene od zadnjeg "release" izdanja
`BUGS'             Kako prijavljivati bug-ove, o test zbirci programa
`AUTHORS'          Lista GPC autora
`COPYING'          The GNU General Public License - GNU opća javna
                   licenca
`COPYING.LIB'      The GNU Lesser General Public License - GNU manje
                   opća javna licenca


File: gpc-hr.info,  Node: Komponente,  Next: Debugger,  Prev: Dokumentacijske datoteke,  Up: Instaliranje GPC-a

3.2.2 Koje komponente trebam za prevođenje Pascal koda?
-------------------------------------------------------

Kompletiran sustav Pascal prevodioca bi trebao imati barem:

  1. Sam prevodilac, GPC.

  2. editor, asembler, linker (povezivač), program za rad s
     bibliotekama i prijatelje.

  3. C biblioteku. Ako imate C prevodilac (compiler) koji funkcionira,
     onda ovo već imate.

  4. debugger (ispravljač pogrešaka), ako želite debuggirati svoje
     programe.

   Za većinu ljudi, GNU "binutils" i GNU debugger (`gdb') su dobar
izbor, iako biste mogli preferirati i koristiti alatke specifične za
proizvođača.


File: gpc-hr.info,  Node: Debugger,  Next: Libraries,  Prev: Komponente,  Up: Instaliranje GPC-a

3.2.3 Kako da ispravljam moje Pascal programe?
----------------------------------------------

Da biste debuggirali svoje programe, (a) GNU Pascal mora biti u
mogućnosti generirati debug informacije za vašu platformu, i (b) morati
imati debugger koji ju znade razumjeti.

   * Ako `gpc -g -o hello hello.p' daje:
          gpc: -g not supported for this platform
     onda to znači da GPC ne može generirati debugging informacije.
     Obično, instaliranje `gas' (dio GNU binutils) umjesto vašeg
     "sistemskog" asemblera može riješiti problem. Kad konfigurirate
     GCC koji GPC koristi, specificirajte `--with-gnu-as', i - po
     mogućnosti - `--with-gnu-ld' i/ili `--with-stabs'. Više
     informacija može se naći u `INSTALL' datoteci u GNU CC source
     direktoriju.

   * Debugger vašeg sustava ne mora razumjeti debug informacije
     generirane GNU alatkama. U tom slučaju može pomoći instaliranje
     `gdb'-a.

   U najgorem slučaju, ako možete debuggirati programe prevođene GCC-om,
onda biste to trebali moći da to napravite i s GPC-om.

   GNU debugger (`gdb') trenutno nema "Pascal" mod, tako da nije u
mogućnosti prikazati neke Pascal strukture i sl. Dok debuggirate,
molimo primijetite da je Inicijalno Slovo U Svakom Identifikatoru
Veliko Slovo A Ostatak Su Mala Slova. Ako želite prikazati varijablu
`foo' u debuggeru, otipkajte `show Foo' ili `display Foo' namjesto toga.

   Iako je `gdb' izvrstan debugger, njegov user-interface nije baš
svačiji prvi izbor. Ako biste željeli debuggirati pod X11, molimo
pogledajte u comp.windows.x FAQ: "Where can I get an X-based debugger?"
na:
`http://www.faqs.org/faqs/x-faq/part6/section-2.html'

   Neki korisni front-endovi uključuju: XXGDB, tGDB i XWPE. Pogledati:
`http://www.ee.ryerson.ca:8080/~elf/xapps/Q-IV.html'

   Vrlo lijep, ali zahtjevan po resurse je (baziran na Motif-u) DDD:
`http://sol.ibr.cs.tu-bs.de/softech/ddd/'

   Nadalje, RHIDE (*note IDE::) sadrži ugrađenu debugging podršku,
sličnu onoj u IDE od BP-a.


File: gpc-hr.info,  Node: Libraries,  Next: Darovane jedinice,  Prev: Debugger,  Up: Instaliranje GPC-a

3.2.4 Biblioteke - koje bi dodatne biblioteke trebao imati?
-----------------------------------------------------------

Bit će vam potrebne dodatne biblioteke (engl. library) dok prevodite
neke od jedinica (engl. unit). Ove se mogu naći u direktoriju
`http://www.gnu-pascal.de/libs/'.

   Trenutno, tamo su slijedeće biblioteke:

gmp
     Aritmetika za cijele brojeve, racionalne i realne brojeve s
     proizvoljnom veličinom i preciznošću. Koristi ju GMP jedinica.

rx
     Regularni izrazi - podudaranje i supstitucija. Koristi ju RegEx
     jedinica.

ncurses
PDCurses
     Rukovanje terminalom. Koristi ju CRT jedinica. Zavisno od vašeg
     sistema, možete imati slijedeći izbor:

     Unix: Možete prevesti terminalske aplikacije s ncurses i
     aplikacije koje rade u X11 prozoru s PDCurses (iako i terminalska
     aplikacija može, naravno, raditi i pod X11 u xterm-u). Ako želite
     koristiti PDCurses (tj. XCurses), dajte opciju `-DX11' kod
     prevođenja CRT-a.

     Dos sa DJGPP i MS-Windows sa mingw: Samo PDCurses je na
     raspolaganju i bit će podrazumno korišten.

     MS-Windows i Cygwin: PDCurses i ncurses su oboje na raspolaganju.
     PDCurses se koristi podrazumno. Ako želite koristiti ncurses,
     postavite opciju `-DUSE_NCURSES' kod prevođenja CRT-a.

     Drugi sistemi: Molim pogledajte `README' datoteke i instalacijske
     instrukcije PDCurses i ncurses kako bi ste ustanovili koje
     (odnosno koje) se mogu izgraditi na vašem sistemu. Pogledajte
     uvjetne direktive na kraju crt.inc i crtc.h (i promijenite ih ako
     je neophodno) koje odlučuju koja će biblioteka biti podrazumno
     korištena (odnosno engl. default).

intl
     Internationalizacija. Koristi ju Intl jedinica. Na nekim sistemima
     to je dio sistemske biblioteke (libc).

ElectricFence
     Ova se biblioteka ne koristi ni od jedne GPC jedinice. Ona je
     debugging alat namijenjen da vam pomogne u pronalaženju bugova s
     alokacijom memorije. Da bi ju koristili samo je povežite
     ("polinkajte") u svoj program, bilo s komandne linije
     (`-lefence'), bilo u samom kodu (`{$L efence}') što biste mogli
     poželjeti staviti unutar jednog `{$ifdef DEBUG}' ili nečeg sličnog
     jer se korištenje libefence preporuča samo za debugging (odnosno
     ispravljanje pogrešaka).

   Izvorni kod biblioteka je na raspolaganju u glavnom `libs'
direktoriju. Većina biblioteka dolazi s jednom ili nekoliko patcheva
(zakrpa, nadopuna) koje treba aplicirati prije njihovog prevođenja.

   Binarne distribucije za neke platforme su na raspolaganju u
`binary/PLATFORM' poddirektorijima. Ako prevodite biblioteke za druge
platforme, osjećajte se dobrodošli da stavite binarne datoteke nama na
raspolaganje za distribuciju na WWW poslužitelju.

   Tamo su također slijedeće datoteke:

`terminfo-linux.tar.gz'
     Ovo je patch (zakrpa) koja omogućava ncurses programima da
     iskoriste sposobnost Linux 2.2 i novijih kernela (jezgri
     operacijskog sustava) da proizvedu blok kursor kad je potrebno.
     Dani patch može biti instaliran bez potrebe da se išta ponovno
     prevodi, samo kopiranjem nekih datoteka na njihovo mjesto. Više
     detalja može se naći u `README' datoteci uključenoj u ovu arhivu.
     Patch neće naškoditi starijim kernelima. Molimo primijetite da
     *nije* samo na Linux strojevima korisno instalirati patch.
     Instaliranje na ostale strojeve će omogućiti korisnicima koji
     koriste telnet sa Linux konzole da profitiraju od blok kurzor
     sposobnosti. Osim toga, neki Unix sistemi imaju instalirane
     starije Linux terminfo zapise ili čak nikakve, tako da je dobra
     stvar, u svakom slučaju, dati im trenutnu verziju.  Patch je
     uključen u terminfo bazu podataka ncurses verzije 5.0, tako da ako
     instalirate ncurses 5.0 (iz source ili binarne distribucije), ne
     trebate posebno dobavljati patch. Ali ga možete instalirati na
     sistem sa starijom ncurses verzijom ako se ne osjećate raspoloženi
     za nadogradnju kompletnih ncurses.

`tsort-2.9i.zip'
     Mali utility programčić (ekstrahiran iz util-linux-2.9i, ali ne
     Linux-specifičan, potreban za konfiguraciju rx biblioteke. Potreban
     vam je samo ako prevodite rx sami (i nije već prisutan na vašem
     sistemu), ne ako koristite rx binarnu distribuciju.


File: gpc-hr.info,  Node: Darovane jedinice,  Next: IDE,  Prev: Libraries,  Up: Instaliranje GPC-a

3.2.5 Darovane jedinice
-----------------------

Nekoliko programera je darovalo jedinice za GPC. One su obično oglašene
na email listi, *Note Mailing List::. Većina njih može se naći na
`http://www.gnu-pascal.de/contrib/'.


File: gpc-hr.info,  Node: IDE,  Prev: Darovane jedinice,  Up: Instaliranje GPC-a

3.2.6 Možete li preporučiti integriranu razvojnu okolinu (IDE)?
---------------------------------------------------------------

Korisnici Borland Pascala se mogu zapitati da li postoji neki
nadomjestak za IDE (Integrated Development Environment). Evo nekoliko
sugestija:

   * (X)Emacs. Neki ljudi misle da je Emacs odgovor na pitanje Života,
     Univerzuma i Svega Ostalog, drugi su odlučili da je GNUsan.
     Dostupan na vašem prijateljski raspoloženom GNU mirror-u i u
     većini distribucija.

   * PENG. Nije free software, ali je pisan s GPC-om. Vrlo je sličan
     Borland-ovom IDE-u, ali s mnogim proširenjima. Binarne distribucije
     za DJGPP, Linux i Solaris mogu se naći na
     `http://fjf.gnu.de/peng/'.

   * RHIDE. DJGPP korisnici mogli bi isprobati RHIDE. Posljednja (beta)
     verzija je kompatibilna s GNU Pascalom i omogućava step, trace i
     watch funkcije poput onih u Borland IDE-u. Može se naći na
     `http://www.rhide.com'.

   * DevPascal. DevPascal je free software IDE za mingw32 platformu.
     Može se naći na `http://www.gnu-pascal.de/contrib/chief/' ili
     `http://www.bloodshed.net/devpascal.html'

   * XWPE je još jedna imitacija Borland IDE-a, tako da je korisnici
     Borland Pascala mogu ocijeniti kao dobru alternativu.


File: gpc-hr.info,  Node: GPC na DJGPP-u,  Next: Znakovni nizovi u GPC-u,  Prev: Instaliranje GPC-a,  Up: FAQ

3.3 GNU Pascal na DJGPP (MS-DOS) platformi
==========================================

Ovo poglavlje raspravlja neke potencijalne probleme s GNU Pascalom na
MS-DOSu, koristeći DJGPP.

* Menu:

* Što je DJGPP::                 Što je DJGPP?
* DJGPP FAQ::                    Ako trebate više informacija
* DJGPP download::               Što download-ati?
* Instaliranje GPC-a na DJGPP::  Kako instalirati prevodilac?
* DJGPP Info reader::            Ne mogu čitati info dokumentaciju!
* DJGPP DPMI server::            GPC kaže: no DPMI
* Asemblerska sintaksa::         Imam problema s asemblerskim kodom ...
* DJGPP-specifičan kod::         Reci mi kako da koristim DPMI, BIOS i
                                 ostale stvari povezane s DOS-om
* Veličina stoga (stack)::       Dobio sam ``exception'' kod pristupanja
                                 `array [1 .. 4000000] of Byte'.


File: gpc-hr.info,  Node: Što je DJGPP,  Next: DJGPP FAQ,  Up: GPC na DJGPP-u

3.3.1 Što je DJGPP?
-------------------

Slijedeći paragraf je preuzet sa site-a `http://www.delorie.com/djgpp/':

   DJGPP je kompletan 32-bit C/C++ razvojni sistem na Intel 80386 (i
višim) PC-jima koji vrte DOS. Uključuje prijenos mnogih GNU razvojnih
alatki. Razvojne alatke zahtijevaju 80386 ili novije računalo, kao i
programi koje one proizvode. U najvećem broju slučajeva, programi koje
proizvodi se mogu komercijalno prodavati bez licence ili taksi.


File: gpc-hr.info,  Node: DJGPP FAQ,  Next: DJGPP download,  Prev: Što je DJGPP,  Up: GPC na DJGPP-u

3.3.2 Ako trebate više informacija
----------------------------------

GPC/DJGPP je DJGPP V2 aplikacija, i većina DJGPP dokumentacije se
odnosi na na GPC. Izvrstan izvor informacija je DJGPP FAQ:
`http://www.delorie.com/djgpp/v2faq/230b.zip'

   Drugo mjesto za traženje DJGPP dokumentacije je DJGPP Knowledge Base,
na slijedećem URL-u: `http://www.delorie.com/djgpp/doc/kb/'


File: gpc-hr.info,  Node: DJGPP download,  Next: Instaliranje GPC-a na DJGPP,  Prev: DJGPP FAQ,  Up: GPC na DJGPP-u

3.3.3 Što download-ati?
-----------------------

Kao što je rečeno u *Note Komponente::, osim samog GPC-a, trebate još i
asembler, linker i prijatelje, C biblioteku i po mogućnosti debugger.
`http://www.delorie.com/djgpp/' preporuča slijedeće datoteke i oni će
vam pomoći naći mirror:

`v2/djdev203.zip'       (C biblioteka)
`v2gnu/bnu2951b.zip'    (asembler, ...)
`v2gnu/gcc2952b.zip'    (gcc)
`v2gnu/gdb418b.zip'     (debugger)
`v2gnu/mak379b.zip'     (make)
`v2gnu/txi40b.zip'      (texi)

   Ova lista čini oko 10 MB ne brojeći GPC. Možete koristiti binarnu
verziju GPC-a s web poslužitelja.


File: gpc-hr.info,  Node: Instaliranje GPC-a na DJGPP,  Next: DJGPP Info reader,  Prev: DJGPP download,  Up: GPC na DJGPP-u

3.3.4 Kako instalirati prevodilac?
----------------------------------

Ako nemate DJGPP instaliran na svom hard disku, kreirajte direktorij za
GNU Pascal (`c:\gpc'), i raspakirajte arhive. Pazite da sačuvate
strukturu direktorija (koristite npr. `pkunzip -d'). Sada, dodajte
direktorij gdje se nalazi `gpc.exe' (`c:\gpc\bin') vašem putu (`$PATH'),
zatim postavite DJGPP environment varijablu tako da pokazuje na vašu
`djgpp.env' datoteku:

     set DJGPP=c:\gpc\djgpp.env

   Zatim, dodajte ovo u vašu `djgpp.env' datoteku:

     ---------------------------------------------------------
     [gpcpp]
     C_INCLUDE_PATH=%/>;C_INCLUDE_PATH%%DJDIR%/lang/pascal;%DJDIR%/include

     [gpc]
     COMPILER_PATH=%/>;COMPILER_PATH%%DJDIR%/bin
     LIBRARY_PATH=%/>;LIBRARY_PATH%%DJDIR%/lib;%DJDIR%/contrib/grx20/lib
     ---------------------------------------------------------

   GPC online dokumentacija je u GNU info formatu; potreban vam je
info-reader (`txi390b.zip') da ga pročitate, ili koristite ugrađeni
info-reader iz RHIDE ili PENG IDE. Da biste dodali GPC dokumentaciju u
info "directory" datoteku, editirajte datoteku `c:\gpc\info\dir', i
nađite slijedeći odlomak:

     ---------------------------------------------------------
     * GCC: (gcc.inf).
     The GNU C, C++, and Objective-C Compiler

     * GDB: (gdb.inf).
     The GNU Debugger (gdb and gdb-dpmi).

     ---------------------------------------------------------

   Da biste dodali GPC, promijenite ove retke tako da izgledaju ovako:

     ---------------------------------------------------------
     * GCC: (gcc.inf).
     The GNU C, C++, and Objective-C Compiler

     * GPC: (gpc.inf).
     The GNU Pascal Compiler

     * GDB: (gdb.inf).
     The GNU Debugger (gdb and gdb-dpmi).

     ---------------------------------------------------------

   Specifične informacije za situacije s malo memorije i još više toga
mogu se pronaći u DJGPP FAQ i dokumentaciji.


File: gpc-hr.info,  Node: DJGPP Info reader,  Next: DJGPP DPMI server,  Prev: Instaliranje GPC-a na DJGPP,  Up: GPC na DJGPP-u

3.3.5 Ne mogu čitati info dokumentaciju!
----------------------------------------

Da biste čitali Info dokumentaciju, potreban vam je `info' program,
`txi390b.zip' ili neka integrirana razvojna okolina (IDE) poput RHIDE
ili PENG.


File: gpc-hr.info,  Node: DJGPP DPMI server,  Next: Asemblerska sintaksa,  Prev: DJGPP Info reader,  Up: GPC na DJGPP-u

3.3.6 GPC kaže: no DPMI
-----------------------

Nemate instaliran DPMI server, a DJGPP v2 zatijeva da je on pokrenut.
Možete ili koristiti neki od komercijalnih DPMI servera (npr.
pokrećite `gpc' u DOS prozoru pod MS-Windowsima), ili download-ajte i
instalirajte CWSDPMI (`csdpmi3b.zip') koji je free DPMI server napisan
za DJGPP.


File: gpc-hr.info,  Node: Asemblerska sintaksa,  Next: DJGPP-specifičan kod,  Prev: DJGPP DPMI server,  Up: GPC na DJGPP-u

3.3.7 Imam problema s asemblerskim kodom ...
--------------------------------------------

GNU asembler (`as.exe'), ili `gas', kojeg poziva GCC prihvaća "AT&T"
sintaksu koja je različita od "Intel" sintakse.  Razlike su pojašnjene
u odlomku 17.1 DJGPP FAQ-a.

   Na rapolaganju je vodič kojeg je napisao Brennan Mr. Wacko Underwood
<brennan@mack.rt66.com>, a opisuje kako koristiti "inline" asemblerske
instrukcije s DJGPP-om, na ovom URL-u:
`http://www.delorie.com/djgpp/doc/brennan/brennan_att_inline_djgpp.html'

   Postoji također i GPC asemblerski vodič, na adresi
`http://www.gnu-pascal.de/contrib/misc/gpcasm.zip'

   Odlomak 17.3 DJGPP FAQ-a opisuje neke metode pretvaranja "Intel"
sintakse u "AT&T" sintaksu.

   Međutim, molimo primijetite da asemlerski kod nije prenosiv, tj.
radit će na IA32 ("x86") i kompatibilnim procesorima, ali neće se čak
ni prevesti na drugim procesorima. Dakle umećući asemblerske
instrukcije u svoje programe, znatno ćete smanjiti njihovu korisnost.

   Ako mislite da zaiste "trebate" asemblerski kod radi brzine - i
provjerili ste da se asemblerski kod zaista vrti brže nego Pascal kod
sa prikladnim optimizacijama - mogli biste poželjeti oboje, i Pascal i
asemblersku verziju, i dozvoliti npr. da jedan `{$ifdef i386}' odlučuje
koju će koristiti. Na ovaj način, program će se barem prevesti na svim
procesorima.


File: gpc-hr.info,  Node: DJGPP-specifičan kod,  Next: Veličina stoga (stack),  Prev: Asemblerska sintaksa,  Up: GPC na DJGPP-u

3.3.8 Reci mi kako da koristim DPMI, BIOS i ostale stvari povezane s DOS-om
---------------------------------------------------------------------------

DPMI, BIOS i ostale funkcije ne razlikuju se od ostalih sistemskih
funkcija. Pogledajte u GPC priručnik kako pristupiti C biblioteci svog
sustava. Ovaj mali primjer pokazuje kako koristiti DPMI, kopirajući
neke strukture i prototipove iz `<dpmi.h>':

     program DPMIDemo;

     { Samo za DJGPP }

     {$X+}

     { `Byte' je `unsigned char' u C-u,
       `ShortCard' je `unsigned short' u C-u,
       `MedCard' je `unsigned long' u C-u,
       `Word' je `unsigned' u C-u,
       itd. (svi ovi tipovi su ``built-in''). }

     type
       TDpmiVersionRet = record
         Major     : Byte;
         Minor     : Byte;
         Flags     : ShortCard;
         CPU       : Byte;
         Master_PIC: Byte;
         Slave_PIC : Byte;
       end;

     type
       TDpmiFreeMemInfo = record
         LargestAvailableFreeBlockInBytes,
         MaximumUnlockedPageAllocationInPages,
         MaximumLockedPageAllocationInPages,
         LinearAddressSpaceSizeInPages,
         TotalNumberOfUnlockedPages,
         TotalNumberOfFreePages,
         TotalNumberOfPhysicalPages,
         FreeLinearAddressSpaceInPages,
         SizeOfPagingFilePartitionInPages,
         Reserved1,
         Reserved2,
         Reserved3: MedCard;
       end;

     function DpmiGetVersion (var Version: TDpmiVersionRet): Integer;
              external name '__dpmi_get_version';

     function DpmiGetFreeMemoryInformation
              (var MemInfo: TDpmiFreeMemInfo): Integer;
              external name '__dpmi_get_free_memory_information';

     var
       Version: TDpmiVersionRet;
       MemInfo: TDpmiFreeMemInfo;

     begin
       if DpmiGetVersion (Version) = 0 then
         begin
           WriteLn ('CPU type:       ', Version.CPU, '86');
           WriteLn ('DPMI major:       ', Version.Major);
           WriteLn ('DPMI minor:       ', Version.Minor);
         end
       else
         WriteLn ('Error in DpmiGetVersion');
       if DpmiGetFreeMemoryInformation (MemInfo) = 0 then
         WriteLn ('Free DPMI memory: ',
                  MemInfo.TotalNumberOfFreePages, ' pages.')
       else
         WriteLn ('Error in DpmiGetMemoryInformation');
     end.


File: gpc-hr.info,  Node: Veličina stoga (stack),  Prev: DJGPP-specifičan kod,  Up: GPC na DJGPP-u

3.3.9 Dobio sam "exception" kod pristupanja `array [1 .. 4000000] of Byte'
--------------------------------------------------------------------------

Po "default-u", maksimalna veličina stoga DJGPP aplikacije je 256K.
Ako trebate više, to trebate podesiti sa stubedit programom, npr.

     stubedit your_app.exe minstack=5000K

   Drugačiji način je da dodate slijedeći kod vašem programu kako bi
definirali minimalnu veličinu stoga (ovdje: 2 MB). Ova će vrijednost
biti poštovana čak i ako korisnik postavi manje vrijednosti koristeći
stubedit, tako da bi ova metoda mogla biti nešto sigurnija. (Ime
linkera `_stklen' je esencijalno; ime korišteno u Pascalu nije od
značaja. Konstanta se ne mora koristiti bilo gdje u programu.
Preporučuje se da ovu deklaraciju stavite u glavnu programsku datoteku,
ne u beku jedinicu/modul, tako da programi koji koriste modul/jedinicu
mogu postaviti koji god limit im je potreban.)

     {$ifdef __GO32__}
     const
       MinStackSize: Cardinal = $200000; attribute (name = '_stklen');
     {$endif}

   Svejedno, mogla bi biti dobra ideja koristiti pokazivače ("pointer")
na velike strukture, i alocirati memoriju dinamički za vrijeme
izvršavanja.

   DJGPP mora alocirati stog u fizičkoj memoriji za vrijeme pokretanja
programa, dakle treba biti oprezan s prevelikim proširenjima stoga.
Većina drugih sistema alocira stranice stoga "on demand", kada ih
program traži, pa je jedini razlog da se uopće postavi ograničenje taj
da se spriječi da podivljala rekurzija pojede svu memoriju ...

   Na Unix-olikim sustavima, možete postaviti "resource limit", ali to
obično ne radite u normalnim programima, nego radije u postavkama
ljuske (bash: `ulimit'; csh: `limit'; sistemski poziv: `setrlimit'(2)).


File: gpc-hr.info,  Node: Znakovni nizovi u GPC-u,  Next: Traženje pomoći,  Prev: GPC na DJGPP-u,  Up: FAQ

3.4 Nizovi
==========

* Menu:

* String schema::                       Čemu sva ta zbrka oko nizova?
* Nizovi u variant record-ima::         Preklapanje nizova u variant record-ima
* Bajt za duljinu::                     Zašto `s[0]' ne sadržava duljinu?
* Nizovi kao parametri po vrijednosti:: Pažnja sa znakovnim nizovima kao
                                          parametrima
* Kratki znakovni nizovi::              Podrška za BP kompatibilne kratke
                                          znakovne nizove
* C znakovni nizovi::                   Što sa C znakovnim nizovima?


File: gpc-hr.info,  Node: String schema,  Next: Nizovi u variant record-ima,  Up: Znakovni nizovi u GPC-u

3.4.1 Čemu sva ta zbrka oko nizova?
-----------------------------------

Znakovni nizovi u Turbo Pascalu imaju bajt koji označava duljinu, na
samom početku. Kako je vrijednost bajta u opsegu 0 .. 255, to ograničava
znakovne nizove na 255 znakova. Međutim, u Pascal shemi znakovni niz je,
kao što je definirano odlomkom 6.4.3.3.3 ISO 10206 Extended Pascal
standarda, "schema record":

     type
       String (Capacity: Integer) = record
         Length: 0 .. Capacity;
         String: packed array [1 .. Capacity + 1] of Char
       end;

   Ovaj `+ 1' je GPC ekstenzija da bi se učinilo mogućim da se
automatski dodaje `#0' "terminator" kad se proslijeđuje ili ih se
dodjeljuje CString-ovima. Tako uz trošak od malo dodatne kompleksnosti
(mora se deklarirati kapacitet niza, ne koristite `GetMem' bez
eksplicitne inicijalizacije člana `Capacity', i dodatnog zahtjeva na
prostor) sada možete imati vrlo dugačke znakovne nizove.


File: gpc-hr.info,  Node: Nizovi u variant record-ima,  Next: Bajt za duljinu,  Prev: String schema,  Up: Znakovni nizovi u GPC-u

3.4.2 Preklapanje nizova u variant record-ima
---------------------------------------------

Q: Da li bi različite varijante u varijant record-u trebale zapadati u
istu memorijsku lokaciju? Prethodni Pascali koje sam koristio su ovo
garantirali, i napisao sam low-level kod koji se oslanja na to.
Varijante nisu iste duljine, niti je bila namjera da budu.

   A: Ne, namjerno je učinjeno da diskriminante nisu preklopljene u
memoriji, da bi se one mogle biti ispravno inicijalizirati prije svega.
Razmotrite:

     record
     case Boolean of
       False: (s1: String (42));
       True:  (s2: String (99));
     end;

   Ako bi se nizovi preklapali, posebno bi njihove diskriminante
zauzimale isto mjesto u memoriji. Kako bi onda trebale biti
inicijalizirane? Na bilo koji način, bilo bi krivo za barem jednu od
varijanti ...

   Dakle, nakon diskusije u ISO Pascal newsgroup-i
(news:comp.lang.pascal.ansi-iso) gdje se ovo pitanje pojavilo u vezi s
varijablama (koje također zahtijevaju nešto automatske inicijalizacije
i finalizacije), odlučili smo da napravimo ovo u GPC-u za sve tipove s
automatskom inicijalizacijom i finalizacijom (trenutno datoteke,
objekti i sheme (schemata), uključujući i znakovne nizove, u budućnosti
bi to također mogle biti i Delphi kompatibilne klase i finalizirani
tipovi), budući da standard ionako ne garantira za iste da su u
preklapanom memorijskom području (engl. overlay) ...

   Postoje dva načina u GPC-u da se dobije garantirano preklapanje
memorije (oba nestandardna, naravno, budući da standard ne pretpostavlja
ništa o internim reprezentacijama; ali su oba BP-kompatibilna),
`absolute' deklaracije i varijabilno dodjeljivanje tipova (variable
type casts). Npr. da bi se preklapalo polje bajtova `b' sa varijablom
`v':

     var
       b: array [1 .. SizeOf (v)] of Byte absolute v;

   Ili možete koristiti dodjelu tipa:

     type
       t = array [1 .. SizeOf (v)] of Byte;

   nakon čega `t (v)' može biti korišten kao polje preklopljeno (u
memoriji se nalazi na istom mjestu) sa `v'.


File: gpc-hr.info,  Node: Bajt za duljinu,  Next: Nizovi kao parametri po vrijednosti,  Prev: Nizovi u variant record-ima,  Up: Znakovni nizovi u GPC-u

3.4.3 Zašto `s[0]' ne sadržava duljinu?
---------------------------------------

Q: U standardnom Pascalu možete očekivati da se `s[1]' podudara sa
pozicijom prvog znaka u nizu `s' i tako jedan znak ulijevo je duljina
od `s'. Tako je `s[0]' jednak duljini od `s'.  Istina?

   A: Ovo stoji za UCSD/BP znakovne nizove (koje GPC još ne
implementira, ali to je u planu). Jedini nizovi koje Standard Pascal
podržava su polja znakova bez ikakvog polja za duljinu.

   GPC također podržava Extended Pascal znakovnu shemu (*note String
schema::), ali one također nemaju bajt koji sadrži duljinu na "poziciji
0", nego radije jedan `Length' član (koji je veći od jednog bajta).


File: gpc-hr.info,  Node: Nizovi kao parametri po vrijednosti,  Next: Kratki znakovni nizovi,  Prev: Bajt za duljinu,  Up: Znakovni nizovi u GPC-u

3.4.4 Pažnja sa znakovnim nizovima kao parametrima
--------------------------------------------------

Q: Postoje li neki skriveni problemi s parametrima - znakovnim nizovima?

   A: Budite oprezni kad prosljeđujete znakovne nizove potprogramima
koje prihvaćaju znakovni niz kao parametar po vrijednosti i onda
interno modificiraju vrijednost parametra. Unutar rutine, parametar po
vrijednosti dobiva fiksan kapacitet - duljinu znakovnog niza u
navodnicima koja mi je proslijeđena. Bilo kakav pokušaj da se dodijeli
duža vrijednost neće uspjeti.

   Ovo vrijedi samo ako je parametar po vrijednosti deklariran kao
`String'. Ako je deklariran kao znakovni niz sa danim kapacitetom (npr.
`String (255)'), tada dobiva ovaj kapacitet unutar rutine.


File: gpc-hr.info,  Node: Kratki znakovni nizovi,  Next: C znakovni nizovi,  Prev: Nizovi kao parametri po vrijednosti,  Up: Znakovni nizovi u GPC-u

3.4.5 Podrška za BP kompatibilne kratke znakovne nizove
-------------------------------------------------------

Q: Dvije različite vrste znakovnih nizova nose isto ime - `String' - to
radi malo konfuzije. Možda bi znakovni nizovi u starom stilu trebali
biti preimenovani u `short string'?

   A: Kada implementiramo kratke nizove, morat ćemo napraviti ovakvu
razliku. Naš trenutačan plan ide ovako:

   `String (N)': string shema (EP kompatibilna)

   `String [N]': kratki znakovni niz (UCSD/BP kompatibilan, gdje N mora
biti <= 255)

   `String': zavisno od prekidača i zastavica prevodioca, po defaultu
shema bez diskriminante, ali u BP modu (ili sa specijalnim prekidačem)
kratki niz kapaciteta 255 (UCSD/BP kompatibilan).

   Q: Kada će ti kratki nizovi biti na raspolaganju?

   A: Planira se već duže od godine. Zakašnjenje je uzrokovano
problemima koji su više pritiskali tim.


File: gpc-hr.info,  Node: C znakovni nizovi,  Prev: Kratki znakovni nizovi,  Up: Znakovni nizovi u GPC-u

3.4.6 Što sa C znakovnim nizovima?
----------------------------------

C znakovni niz (`char *') je polje znakova, završeno s `#0' znakom.

   Funkcije C biblioteke zahtijevaju C, ne Pascal string argumente.
Međutim, znakovni nizovi u Pascal stilu se automatski pretvaraju u one
u C stilu kada se prosljeđuju rutinama koje očekuju znakovne nizove u C
stilu. Ovo radi jedino ako rutina samo čita iz znakovnog niza, ne ako
ga ona modificira.

   Npr. to je način kako ćete pozvati `system()' poziv u vašoj C
biblioteci (što više nije neophodno, otkad je već ugrađen `Execute'):

     program SysCall;

     function System (CmdLine: CString): Integer; external name 'system';

     var
       Result: Integer;

     begin
       Result := System ('ls -l');
       WriteLn ('system() call returned: ', Result)
     end.

   Mogli biste koristiti tip `PChar' umjesto `CString'. I `CString' i
`PChar' su oboje definirani kao `^Char' - iako mi preporučujemo
`CString' jer to čini jasnijim da govorimo o nekakvom nizu prije nego o
jednom jedinom znaku.

   Mnogo rutina iz biblioteke u Pascalu za mnoge aplikacije postoji u
GPC jedinici i u nekim drugim jedinicama. Kad god je to moguće, trebalo
bi ove koristiti (npr. `Execute' radije nego `system()', i tada se ne
trebate brinuti o `CString'-ovima.

   Molimo *NE* prosljeđivati C znakovne nizove kao `const' ili `var'
parametar ako C prototip kaže `const char *' ili ćete vjerojatno dobiti
"Segmentation fault" pogrešku.


File: gpc-hr.info,  Node: Traženje pomoći,  Next: FAQ "Razno",  Prev: Znakovni nizovi u GPC-u,  Up: FAQ

3.5 Traženje pomoći
===================

Molimo pročitajte GPC priručnik (info datoteke ili drugi format) kao i
`README' i `BUGS' datoteke koje dolaze s GPC-om (obično instalirane u
direktoriju `/usr/local/doc/gpc'), plus ostalu dokumentaciju koja bi
mogla pomoći (DJGPP FAQ ako koristite DJGPP, i sl.) prije nego
pošaljete email timu za održavanje ili na mailing listu.

   Posebno, `BUGS' datoteka sadrži informacije kako poslati prijavu
buga na najefikasniji način.

   `Support' poglavlje GPC priručnika reći će vam gdje da nađete više
informacija o GPC-u u kako kontaktirati GPC razvojni tim.  (*note
Support::)


File: gpc-hr.info,  Node: FAQ "Razno",  Prev: Traženje pomoći,  Up: FAQ

3.6 Razno
=========

* Menu:

* Suradnja na projektu::   Želio bih doprinijeti projektu; što sad?
* GPC web poslužitelj::    Gdje je GNU Pascal web poslužitelj?
* O ovom FAQ-u::           O ovom FAQ-u.


File: gpc-hr.info,  Node: Suradnja na projektu,  Next: GPC web poslužitelj,  Up: FAQ "Razno"

3.6.1 Želio bih doprinijeti projektu; što sad?
----------------------------------------------

Ako biste željeli surađivati na projektu, molimo pišite na mailing
listu, *Note Mailing List::.


File: gpc-hr.info,  Node: GPC web poslužitelj,  Next: O ovom FAQ-u,  Prev: Suradnja na projektu,  Up: FAQ "Razno"

3.6.2 Gdje je GNU Pascal web poslužitelj?
-----------------------------------------

GPC homepage na webu, za informacije i download, je na
`http://www.gnu-pascal.de'.

   GPC "To-Do" lista, sa najnovijim mogućnostima i ispravljenim
bugovima može se naći tamo.


File: gpc-hr.info,  Node: O ovom FAQ-u,  Prev: GPC web poslužitelj,  Up: FAQ "Razno"

3.6.3 O ovom FAQ-u
------------------

Trenutno održava: Russ Whitaker, <russ@ashlandhome.net>

   Ovo je druga inkarnacija GNU Pascal FAQ liste, bazirano na prethodnom
FAQ-u kojeg je napisao J.J. van der Heijden. Komentari, sugestije ili
korekcije ovoj listi često postavljanih pitanja su uvijek dobrodošle.

   Molimo uključite u svoju email poruku i broj verzije dokumenta na
koji se vaši komentari odnose (možete naći broj verzije na početku ove
FAQ liste).

   Mnogi su ljudi doprinijeli ovom FAQ-u, samo neki od njih su
spomenuti gore. Mnogo informacija u njemu, kao i inspiracija za ovu FAQ
listu su uzeta s prometa GPC mailing liste, tako da ste mogli (a da
niste niti znali) doprinijeti ovoj listi.


File: gpc-hr.info,  Node: Installation,  Next: Invoking GPC,  Prev: FAQ,  Up: Top

4 How to download, compile and install GNU Pascal.
**************************************************

* Menu:

* Download::              Where and what to download
* Binary Distributions::  How to install a binary distribution
* Compiling GPC::         How to compile GPC
* Compilation Notes::     Compilation notes for specific platforms
* Cross-Compilers::       Building and Installing a cross-compiler
* Crossbuilding::         Crossbuilding a compiler


File: gpc-hr.info,  Node: Download,  Next: Binary Distributions,  Up: Installation

4.1 Where and what to download
==============================

You can download the source code of the current GNU Pascal release from
     `http://www.gnu-pascal.de/current/'
   and binaries for some platforms from
     `http://www.gnu-pascal.de/binary/'

   The binary archive files are named `gpc-VERSION.PLATFORM.EXTENSION'
- for example `gpc-2.1.alpha-unknown-linux-gnu.tar.gz' for GPC version
2.1 on an Alpha workstation running the Linux kernel with GNU C
Library, or `gpc-20000616.i386-pc-msdosdjgpp' for GPC version 20000616
on an Intel IA32 compatible PC running DOS with DJGPP.

   After you have downloaded the correct archive file for your
platform, please read the installation notes on how to install such a
binary distribution.

   If you are running Dos or MS Windows, you will need additional tools
- see "What else to download and where" below.

Current snapshots
-----------------

GNU Pascal is subject to steady development. Alpha and beta snapshots
(source only, use at your own risk) can be found at:

     `http://www.gnu-pascal.de/alpha/'
     `http://www.gnu-pascal.de/beta/'

What else to download and where
-------------------------------

When you are using GNU Pascal on a DOS system, you will need either the
DJGPP or the EMX development environment (see below). On an OS/2
system, you will need EMX. On an MS Windows 95/98/NT system you will
need either the CygWin or the mingw32 ot the MSYS environment.

   GNU Pascal uses the compiler back-end from the GNU Compiler
Collection, GNU CC or GCC. If you want to compile GPC, you will need
the source of GCC as well as the source of GPC itself. From the same
place as GPC, please download GCC `2.8.1, 2.95.x, 3.2.x, 3.3.x or
3.4.x'. (It is also available from any GNU mirror; see
`http://www.gnu.org/software/gcc/'.)

Libraries
---------

For some of GPC's units, you will need some standard libraries. In
particular:

Unit             Platform              Library
CRT              Unix/terminal         ncurses >= 5.0 (1), (2)
CRT              Unix/X11              PDCurses (2)
CRT              Dos, MS-Windows       PDCurses (3)
GMP              any                   gmp
RegEx            any                   rx
(debugging)      Unix, MS-Windows      ElectricFence (4)

   Notes:

   (1) ncurses version 5.0 or newer is strongly recommended because
older versions contain a bug that severely affects CRT programs.

   (2) You can install both ncurses and PDCurses on a Unix system, and
choose at compile time whether to generate a terminal or X11 version of
your program.

   (3) ncurses also runs under MS-Windows with CygWin (not mingw32,
however), but doesn't appear to behave much differently from PDCurses
on that platform.

   (4) ElectricFence is not used by any unit, but can be used for
debugging memory allocation bugs by simply linking it (see the
accompanying documentation).

   You can find those libraries on many places on the Net. Also, many
GNU/Linux distributions, DJGPP mirrors and other OS distributions
already contain some of the libraries. In any case, you can find the
sources of the libraries (sometimes together with patches that you
should apply before building if you choose to build from the sources)
and binaries for some platforms in

     `http://www.gnu-pascal.de/libs/'

   For more information and descriptions of these libraries, see *Note
Libraries::.

DJGPP
-----

DJGPP (http://www.delorie.com/djgpp/) is available from any SimTel
mirror in the `gnu/djgpp' subdirectory; for addresses look into the
DJGPP FAQ (http://www.delorie.com/djgpp/v2faq/).  To use GNU Pascal you
need at least

   - the C library, `v2/djdev201.zip', and

   - `binutils' (assembler, etc.), `v2gnu/bnu270b.zip'.

   We also recommend you to get:

   - the `make' utility, `v2gnu/mak375b.zip'

   - the GNU debugger, `v2gnu/gdb416b.zip'

   - the DJGPP FAQ, `v2faq/faq211b.zip'

   - the GRX graphics library, `http://www.gnu.de/software/GRX/'

   - PENG, `http://fjf.gnu.de/peng/', an integrated development
     environment, similar to BP's one, written in GNU Pascal, or

   - RHIDE, `v2app/rhide.zip', another integrated development
     environment, or

   - DevPascal, `http://www.bloodshed.net/devpascal.html', an
     integrated development environment for mingw32.

EMX
---

EMX is an environment for creating 32-bit applications for DOS and OS/2.
To develop EMX programs with GNU Pascal you need at least

   - the EMX runtime package, `emxrt.zip',

   - the EMX development system, `emxdev*.zip', and

   - the GNU development tools, `gnudev*.zip'.

   If your DOS box has DPMI (it does if you are using MS Windows or
OS/2) you will also need RSX, available from the same sites as EMX in
the subdirectory `rsxnt'.

   The GNU development tools contain the GNU C compiler which is in fact
not needed to use GNU Pascal. However, the C library _is_ needed.

CygWin
------

CygWin is an environment which implements a POSIX layer under MS
Windows, giving it large parts of the functionality of Unix. CygWin
contains development tools such as an assembler, a linker, etc. GPC
needs for operation. More information about CygWin can be found at
     `http://cygwin.com'

mingw32
-------

The Minimalists' GNU Win32 environment, mingw32, allows a large number
of Unix programs - including GPC and GCC - to run under MS Windows
95/98/NT using native MS libraries. mingw32 ressources can be found at
     `http://www.mingw.org'


File: gpc-hr.info,  Node: Binary Distributions,  Next: Compiling GPC,  Prev: Download,  Up: Installation

4.2 Installation instructions for a GPC binary distribution
===========================================================

To install a binary distribution, `cd' to the root directory and unpack
the archive while preserving the stored directory structure. Under a
Unix compatible system with GNU `tar' installed, the following
(performed as `root') will do the job:

     # cd /
     # tar xzf ARCHIVE.tar.gz

   If you are using a `tar' utility other than GNU `tar', it might be
necessary to do the above in an explicit pipe:

     # cd /
     # gzip -c -d ARCHIVE.tar.gz | tar xf -

   Some binary distributions are now distributed packed with `bzip2'.
You can recognize them by their file name suffix `.bz2' instead of
`.gz'. For such archives, make sure you have `bunzip2' installed and
then use the following command:

     # cd /
     # tar xjf ARCHIVE.tar.bz2

   Or:

     # cd /
     # bunzip2 -c -d ARCHIVE.tar.bz2 | tar xf -

   If you want to install a GPC binary distribution in another directory
than it was prepared for (for example, if you do not have root access
to the computer and want to install GPC somewhere under your home
directory), you can do the following:

   - Unpack the archive file in a directory of your choice (see above).

   - `cd' to the "prefix" directory of the distribution (for instance
     `usr/local').

   - Run the script `install-gpc-binary', available from
     `http://www.gnu-pascal.de/binary/'.

   - Follow the instructions in the script.

   To install a ZIP archive under DOS with `PKunzip', `cd' to the
appropriate directory (usually `\' for EMX, `\DJGPP' for DJGPP), then
call `PKunzip' with the `-d' option:

     C:\> cd djgpp
     C:\DJGPP> pkunzip -d ARCHIVE.zip

   where `ARCHIVE.zip' is the name of the distribution file.

   For DJGPP you must edit your `djgpp.env' in the `DJGPP' directory to
complete the installation: Please copy the entries from `[gcc]' to
create a new `[gpc]' section. The result may look as follows:

     [gcc]
     COMPILER_PATH=%/>;COMPILER_PATH%%DJDIR%/bin
     LIBRARY_PATH=%/>;LIBRARY_PATH%%DJDIR%/lib

     [gpc]
     COMPILER_PATH=%/>;COMPILER_PATH%%DJDIR%/bin
     LIBRARY_PATH=%/>;LIBRARY_PATH%%DJDIR%/lib

   If you are using the DJGPP version of GPC but do not have a `DJGPP'
directory, please download and install DJGPP (*note Download::).

   Binary distributions include `libgcc.a' and `specs', files that are
normally part of GCC. If you have GCC installed, they will be replaced
unless you manually install the archive.


File: gpc-hr.info,  Node: Compiling GPC,  Next: Compilation Notes,  Prev: Binary Distributions,  Up: Installation

4.3 Compiling GPC
=================

The preferred way to distribute GNU software is distribution of the
source code. However, it can be a non-trivial exercise to build GNU
Pascal on some non-Unix systems, so we also provide ready-to-run
binaries for a number of platforms. (See *Note Binary Distributions::
for how to install a binary distribution.)

   GPC is based on the GNU Compiler Collection, GNU CC or GCC. You will
need the GCC sources to build it. It must be the same version as the
one GPC is implemented with - `2.8.1, 2.95.x, 3.2.x, 3.3.x or 3.4.x' as
of this writing. Although you need GCC to build the GNU Pascal
compiler, you don't need GCC to compile Pascal programs once GNU Pascal
is installed. (However, using certain libraries will require compiling
C wrappers, so it is a good idea to install the C compiler as well.)

   Because GNU Pascal shares its back-end with GCC, it should run on any
system supported by GCC. A full list of platforms supported by GCC can
be found in *Note the GCC installation instructions: (gcc)Installation.

   The GCC source can be obtained from any mirror of the GNU FTP site,
`ftp://ftp.gnu.org/gnu/gcc/'. The "core" distribution is sufficient for
GPC.

   Here is the generic procedure for installing GNU Pascal on a Unix
system. See *Note Compilation Notes:: for extra information needed to
install GPC on DOS-like platforms.

  1. Checking the prerequisites

     Make sure that GNU make is installed and that you use it in the
     following steps. When unsure, you can try `make --version' and/or
     `gmake --version'. It should tell you that it is GNU make. If you
     don't have it, you can obtain it from
     `http://www.gnu.org/software/make/'.

     (In the following, we will simply speak of `make' when invoking
     GNU make; you might need to call `gmake' instead.)

     You also need a `patch' program. If such a program is not
     installed on your system, you can get GNU patch from
     `http://www.gnu.org/directory/patch.html'.

     For extracting the example programs from the documentation to the
     `doc/docdemos' directory a non-crippled `sed' is needed.  GNU sed
     is known to work.

     If you have downloaded a "minimal" source distribution, most
     derived files have to be rebuilt. This is done automatically when
     building GPC, but you need additional tools:

     `bash', `bzip2', *GNU* `sed', GNU `awk', GNU `m4', `bison' (at
     least version 2.0), `flex' (version 2.5.27), `autoconf' (version
     2.12), `texinfo' (at least version 4.2), `help2man'.

     Make sure that these are installed. The minimal distributions are
     compressed with `bzip2' instead of `gzip', so substitute it in the
     instructions below.

     If your bison and flex programs are installed under different
     names, you may have to set some or all of the following environment
     variables before running `configure':

          FLEX=/path/to/flex
          LEX=/path/to/flex
          BISON=/path/to/bison
          YACC=/path/to/bison
          INTLBISON=/path/to/bison

     If you want to build the GPC WWW pages you will also need a TeX
     distribution (including `pdftex' and `dvips').

     If you run into trouble during the installation process, please
     check whether you are using outdated versions of the required
     utilities and upgrade if necessary.

     The GNU versions of the packages above are available from
     `http://www.gnu.org/software/', in a subdirectory whose name is
     the name of the package.

  2. Unpacking the source

     From a directory of your choice (e.g. `/home/fred'), unpack the
     GCC and GNU Pascal source distributions. This will create separate
     subdirectories for GCC and GPC. Let us assume `gcc-2.95.3' and
     `gpc-20030209' in this example.
          % cd /home/fred
          % gzip -c -d gcc-core-2.95.3.tar.gz | tar xf -
          % gzip -c -d gpc-20030209.tar.gz | tar xf -

     `cd' to the GPC directory and move the contents (a subdirectory
     `p') to the subdirectory `gcc' of the GCC directory:

          % mv /home/fred/gpc-20030209/p /home/fred/gcc-2.95.3/gcc/

     Instead of moving the directory, it is now also possible to make a
     symbolic link (if the OS supports symlinks). This is useful if you
     want to build GPC with several different GCC versions:

          % ln -s /home/fred/gpc-20030209/p /home/fred/gcc-2.95.3/gcc/p

     It is recommended, though not required, to use a separate
     directory for building the compiler, rather than compiling in the
     source directory. In this example, let us create
     `/home/fred/gpc-build' for this purpose:

          % mkdir /home/fred/gpc-build

     If you use a separate directory, you do not need to write into the
     GCC source directory once you have patched the GCC source (see
     below), and can build GPC for more than one platform from the same
     source tree.

     In case you are re-using a directory where you have already built
     GCC and/or GPC for a different target machine, do `make distclean'
     to delete all files that might be invalid. One of the files this
     deletes is `Makefile'; if `make distclean' complains that
     `Makefile' does not exist, it probably means that the directory is
     already suitably clean.

  3. Configuring and building GCC

     GNU Pascal is automatically configured with GCC. Configuration of
     GCC is treated in depth in *Note the GCC installation
     instructions: (gcc)Installation.  The normal procedure is as
     follows:

     `cd' to the GPC build directory. From there, run the `configure'
     script in the GCC source directory:

          % cd /home/fred/gpc-build
          % /home/fred/gcc-2.95.3/configure --enable-languages=pascal

     This creates all the necessary config files, links and Makefile in
     the GCC object directory.

     Note 1: The configuration will prompt you for patching the GCC
     source for GPC support, so you need write access to that
     directory. All changes to GCC are surrounded by `#ifdef GPC ...
     #endif', so they should not interfere when you build a C compiler
     from this source tree.

     Note 2: The `--enable-languages=pascal' option means that we only
     want to build the Pascal compiler and not, for instance, the C++
     compiler.

     Note 3: The standard base directory for installing GCC and GPC is
     `/usr/local'. If you want to install files to an alternate
     directory DIR, specify `--prefix=DIR' when you run `configure'.
     For installing into a system directory such as `/usr/local' you
     will, of course, need appropriate permissions (often root).
     Therefore, if you want to install GPC on a system where you don't
     have those permissions, you must specify a prefix (e.g.,
     `$HOME/usr').

  4. Putting other GNU tools in place

     Some environments require other GNU tools (such as the GNU
     assembler or linker) instead of the standard system tools for GCC
     to work. (See the GCC installation instructions for details.) If
     this is the case for your system, install the required tools in
     the GPC build directory under the names `as', `ld', or whatever is
     appropriate. This will enable the compiler to find the proper
     tools for compilation of the program `enquire' (a part of GCC) and
     to install the GNU tools to a place where they are found by GCC
     but do not interfere with the standard system tools.

     Alternatively, you can do subsequent compilation using a value of
     the `PATH' environment variable such that the necessary GNU tools
     come before the standard system tools.

  5. Compiling GPC

     Once you are satisfied with the configuration as determined by
     `configure', you can build the compiler:

          % make

     Notice that this procedure will build the C compiler (and maybe
     some other compilers) too, because that is used to compile the GPC
     runtime library.

     Optionally, you may supply CFLAGS, LDFLAGS or RTSFLAGS. CFLAGS is
     used for compiler and RTS, RTSFLAGS are for RTS only, i.e.: `make
     CFLAGS="-O2" RTSFLAGS=-Wall'

     *Note*: The documentation may fail to build from *.texi sources if
     GCC 2.95.x tries to use an older version of `makeinfo' supplied in
     GCC package itself. This can be prevented by supplying explicit
     instruction to use your system's `makeinfo':

          % make MAKEINFO=`which makeinfo`

     optionally followed by the rest of arguments.

  6. Completing the installation

     When everything has been compiled, you can check the installation
     process with:

          % make -n install

     To complete the installation, run the command `make install'. You
     need write access to the target directories (`/usr/local/bin',
     `/usr/local/lib', `/usr/local/info', `/usr/local/doc', and
     `/usr/local/man' in this example), so this is usually done as
     `root':

          % su -c "make install"

     If you want to install _only_ the Pascal compiler (for example if
     you already have the correct version of GCC installed), `cd' to the
     `gcc' subdirectory of the build directory (e.g.
     `/home/fred/gpc-build/gcc') and run `make pascal.install'. This
     installation process does *not* overwrite existing copies of
     `libgcc.a' or `specs', should they exist.

     However, if you do not have the exactly matching GCC version
     installed, you might need some additional files (otherwise GPC will
     complain about missing files at runtime). You can install them by
     doing `make pascal.install-with-gcc' in the `gcc' subdirectory of
     the build directory.

     There is a (partial) translation of the GPC manual into Croatian
     available now. It is not installed by default. If you want to
     install it, do a `pascal.install-hr' in the `gcc' directory. This
     will install the manpage `gpc-hr.1' and the info documentation
     `gpc-hr.info*'. Other formats like PS, PDF and HTML can be built
     manually (it's also easy to add appropriate make targets for them
     when needed).

     Also from the `gcc' subdirectory you can do some more "exotic"
     builds. For instance, you can build the GPC WWW pages by typing
     `make pascal.html' or a binary distribution by typing `make
     pascal.bindist'. See the `Makefile' in that directory for more
     examples.


File: gpc-hr.info,  Node: Compilation Notes,  Next: Cross-Compilers,  Prev: Compiling GPC,  Up: Installation

4.4 Compilation notes for specific platforms
============================================

* Menu:

* MS-DOS with DJGPP::        The DJGPP port of GNU compilers to MS-DOS.
* MS-DOS or OS/2 with EMX::  The EMX port of GNU compilers to MS-DOS and OS/2.
* MS Windows 95/98/NT::      Installation on a Windows 95/98/NT system.


File: gpc-hr.info,  Node: MS-DOS with DJGPP,  Next: MS-DOS or OS/2 with EMX,  Up: Compilation Notes

4.4.1 MS-DOS with DJGPP
-----------------------

The only compiler that is capable of compiling the GNU Compiler
Collection (GNU CC or GCC) under MS-DOS is GCC itself. In order to
compile GPC or GCC for MS-DOS with DJGPP you will therefore need either
a working copy of DJGPP installed, or you will have to cross-build from
a non-MS-DOS system.

   Building GPC under MS-DOS with DJGPP follows the same scheme as
building GPC under a Unix-like system: Place the `p' subdirectory in the
`gcc' directory and follow the instructions for compiling GCC. This
requires `bash' and many other tools installed, and you must be very
careful at many places to circumvent the limitations of the DOS
platform.

   Our preferred way to build GPC for DJGPP is to cross-build it from a
Unix-like platform - which is much easier. For instructions, see *Note
Cross-Compilers:: and *Note Crossbuilding::.


File: gpc-hr.info,  Node: MS-DOS or OS/2 with EMX,  Next: MS Windows 95/98/NT,  Prev: MS-DOS with DJGPP,  Up: Compilation Notes

4.4.2 MS-DOS or OS/2 with EMX
-----------------------------

EMX is a free 32-bit DOS extender which adds some properties of Unix to
MS-compatible DOS and IBM's OS/2 operating systems.

   As of this writing, we are not aware of current versions of GCC for
EMX, and EMX support in GPC has not been maintained. Please contact us
if you know about recent development in EMX and are interested in
continuing EMX support in GPC.


File: gpc-hr.info,  Node: MS Windows 95/98/NT,  Prev: MS-DOS or OS/2 with EMX,  Up: Compilation Notes

4.4.3 MS Windows 95/98/NT
-------------------------

There are two ports of the GNU development tools to MS Windows
95/98/NT: CygWin and mingw32.

   The CygWin environment implements a POSIX layer under MS Windows,
giving it large parts of the functionality of Unix. Thus, compiling GCC
and GPC under the CygWin environment can be done following the
instructions for compiling it under a Unix-like system (see *Note
Compiling GPC::).

   The Minimalists' GNU Win32 environment, mingw32, uses the native
`crtdll.dll' library of MS Windows. It is much smaller than CygWin, but
it is not self-hosting and must be crossbuilt from another system (see
*Note Crossbuilding::).


File: gpc-hr.info,  Node: Cross-Compilers,  Next: Crossbuilding,  Prev: Compilation Notes,  Up: Installation

4.5 Building and Installing a cross-compiler
============================================

GNU Pascal can function as a cross-compiler for many machines.
Information about GNU tools in a cross-configuration can be found at
`ftp://ftp.cygnus.com/pub/embedded/crossgcc/'.

   Since GNU Pascal generates assembler code, you need a cross-assembler
that GNU Pascal can run, in order to produce object files. If you want
to link on other than the target machine, you need a cross-linker as
well. It is straightforward to install the GNU binutils to act as
cross-tools - see the installation instructions of the GNU binutils for
details.

   You also need header files and libraries suitable for the target
machine that you can install on the host machine. Please install them
under `PREFIX/PLATFORM/include/', for instance
`/usr/local/i386-pc-msdosdjgpp/include/' for a cross-compiler from a
typical Unix-like environment to MS-DOS with DJGPP.

   Configuration and compilation of the compiler can then be done using
the scripts `cfgpc' and `mkgpc' which are included in the source
distribution in the subdirectory `p/script'. Please call them with the
`-h' option for instructions.


File: gpc-hr.info,  Node: Crossbuilding,  Prev: Cross-Compilers,  Up: Installation

4.6 Crossbuilding a compiler
============================

Using a cross-compiler to build GNU Pascal results in a compiler binary
that runs on the cross-target platform. This is called "crossbuilding".
A possible reason why anybody would want to do this, is when the
platform on which you want to run the GNU Pascal compiler is not
self-hosting. An example is mingw32.

   To crossbuild GNU Pascal, you have to install a cross-compiler for
your target first, see *Note Cross-Compilers::.

   As when building a cross-compiler, configuration and compilation of
the compiler can be done using the scripts `cfgpc' and `mkgpc' which
are included in the source distribution in the subdirectory `p/script'.
Please call them with the `-h' option for instructions.


File: gpc-hr.info,  Node: Invoking GPC,  Next: Programming,  Prev: Installation,  Up: Top

5 Opcije u naredbenoj liniji koje podržava GNU Pascal.
******************************************************

(Pozivanje GPC-a).

   GPC je prevodilac (engl. compiler) koji se poziva iz naredbene
(komandne) linije tj. potrebno je pozvati `gpc' prosljeđujući mu ime
datoteke koju želite da prevede, plus (eventualne) opcije.

   GPC podržava sve opcije komandne linije (engl. command-line options)
koje poznaje GCC prevodilac, osim velikog broja opcija za preprocesor.
Za kompletni referentni popis i opis svih opcija pogledajte *Note GCC
Command Options: (gcc)Invoking GCC.  Niže ćete naći listu dodatnih
opcija koje GPC podržava, kao i listu najvažnijih opcija koje GPC
podržava (uključujući i neke on onih koje podržava jednako i GCC).

   Moguće je miješati opcije i imena datoteka u komandnoj liniji. U
većini slučajeva poredak nije bitan. Poredak postaje bitan npr. kad
koristite više opcija istog tipa; za primjer, ako navedete `-L' više
nego jednom, direktoriji (kazala) se pretražuju u poretku u kojem su
specificirani.  _Note:_ Kako mnoge opcije imaju višeslovna imena,
višestruke jednoslovne opcije _ne_ mogu se grupirati na način koji je
moguć u mnogim drugim programima: `-dr' je vrlo različito od `-d -r'.

   Mnoge opcije imaju duga imena koja započinju sa `--' ili, potpuno
ekvivalentno `-f'. Npr. `--mixed-comments' je isto što i
`-fmixed-comments'. Neke opcije upućuju GPC da daje upozorenja (engl.
warnings) tj. dijagnostičke poruke koje izvještavaju o konstrukcijama
koje nisu same u sebi pogrešne, ali su rizične; ili može sugerirati da
je možda došlo do pogreške. Te opcije započinju s `-W'.

   Većina za GPC specifičnih opcija mogu također biti promijenjene
tijekom jedne kompilacije korištenjem naredbi prevodiocu (engl.
compiler directives) u izvornom kodu (engl. source), npr. `{$X+}' ili
`{$extended-syntax}' za `--extended-syntax' (*note Compiler
Directives::).

   GPC razumije iste varijable okoline (engl. environment variables)
koje razumije i GCC (*note Environment Variables Affecting GCC:
(gcc)Environment variables.).  Dodatno, GPC prepoznaje
`GPC_EXEC_PREFIX' sa istim značenjem koje `GCC_EXEC_PREFIX' ima za GCC.
GPC također prepoznaje `GCC_EXEC_PREFIX', ali `GPC_EXEC_PREFIX' ima
veći prioritet.

   Neke od dugih opcija (npr. `--unit-path') trebaju argument
(parametar).  Ovaj je parametar odvojen jednim `=' znakom, npr.

     --unit-path=/home/foo/units

* Menu:

* GPC Command Line Options::    GPC opcije komandne linije osim GCC-ovih.
* GPC Options::                 Najčešće korištene opcije GPC-a.

   (Napomena: naslovi poglavlja su neprevedeni zbog unakrsnih referenci
iz neprevedenih poglavlja priručnika i prema njima.)


File: gpc-hr.info,  Node: GPC Command Line Options,  Next: GPC Options,  Up: Invoking GPC

5.1 GPC opcije osim GCC-ovih.
=============================

Slijedeća tablica navodi opcije komandne linije osim onih koje također
razumije i GCC.

   (Sadržaj se automatski generira na engleskom.)

`--debug-tree'
     (For GPC developers.) Show the internal representation of a given
     tree node (name or address).

`--debug-gpi'
     (For GPC developers.) Show what is written to and read from GPI
     files (huge output!).

`--debug-automake'
     (For GPC developers.) Give additional information about the
     actions of automake.

`--debug-source'
     Output the source while it is being processed to standard error.

`--no-debug-source'
     Do not output the source while it is being processed (default).

`--disable-debug-info'
     Inhibit `-g' options (temporary work-around, this option may
     disappear in the future).

`--progress-messages'
     Output source file names and line numbers while compiling.

`--no-progress-messages'
     Do not output source file names and line numbers while compiling
     (default).

`--progress-bar'
     Output number of processed lines while compiling.

`--no-progress-bar'
     Do not output number of processed lines while compiling (default).

`--automake-gpc'
     Set the Pascal compiler invoked by automake.

`--automake-gcc'
     Set the C compiler invoked by automake.

`--automake-g++'
     Set the C++ compiler invoked by automake.

`--amtmpfile'
     (Internal switch used for automake).

`--autolink'
     Automatically link object files provided by units/modules or `{$L
     ...}' (default).

`--no-autolink'
     Do not automatically link object files provided by
     units/modules/`{$L ...}'.

`--automake'
     Automatically compile changed units/modules/`{$L ...}' files and
     link the object files provided.

`--no-automake'
     Same as `--no-autolink'.

`--autobuild'
     Automatically compile all units/modules/`{$L ...}' files and link
     the object files provided.

`--no-autobuild'
     Same as `--no-autolink'.

`--maximum-field-alignment'
     Set the maximum field alignment in bits if `pack-struct' is in
     effect.

`--ignore-packed'
     Ignore `packed' in the source code (default in `--borland-pascal').

`--no-ignore-packed'
     Do not ignore `packed' in the source code (default).

`--ignore-garbage-after-dot'
     Ignore anything after the terminating `.' (default in
     `--borland-pascal').

`--no-ignore-garbage-after-dot'
     Complain about anything after the terminating `.' (default).

`--extended-syntax'
     same as `--ignore-function-results --pointer-arithmetic
     --cstrings-as-strings -Wno-absolute' (same as `{$X+}').

`--no-extended-syntax'
     Opposite of `--extended-syntax' (same as `{$X-}').

`--ignore-function-results'
     Do not complain when a function is called like a procedure.

`--no-ignore-function-results'
     Complain when a function is called like a procedure (default).

`--pointer-arithmetic'
     Enable pointer arithmetic.

`--no-pointer-arithmetic'
     Disable pointer arithmetic (default).

`--cstrings-as-strings'
     Treat CStrings as strings.

`--no-cstrings-as-strings'
     Do not treat CStrings as strings (default).

`-Wabsolute'
     Warn about variables at absolute adresses and `absolute' variable
     with non-constant addresses (default).

`-Wno-absolute'
     Do not warn about variables at absolute adresses and `absolute'
     variable with non-constant addresses.

`--short-circuit'
     Guarantee short-circuit Boolean evaluation (default; same as
     `{$B-}').

`--no-short-circuit'
     Do not guarantee short-circuit Boolean evaluation (same as
     `{$B+}').

`--mixed-comments'
     Allow comments like `{ ... *)' as required in ISO Pascal (default
     in ISO 7185/10206 Pascal mode).

`--no-mixed-comments'
     Ignore `{' and `}' within `(* ... *)' comments and vice versa
     (default).

`--nested-comments'
     Allow nested comments like `{ { } }' and `(* (* *) *)'.

`--no-nested-comments'
     Do not allow nested comments (default).

`--delphi-comments'
     Allow Delphi style `//' comments (default).

`--no-delphi-comments'
     Do not allow Delphi style `//' comments.

`--macros'
     Expand macros (default).

`--no-macros'
     Do not expand macros (default with `--ucsd-pascal',
     `--borland-pascal' or `--delphi').

`--truncate-strings'
     Truncate strings being assigned to other strings of too short
     capacity.

`--no-truncate-strings'
     Treat string assignments to other strings of too short capacity as
     errors.

`--exact-compare-strings'
     Do not blank-pad strings for comparisons.

`--no-exact-compare-strings'
     Blank-pad strings for comparisons.

`--double-quoted-strings'
     Allow strings enclosed in "\" (default).

`--no-double-quoted-strings'
     Do not allow strings enclosed in "\" (default with dialect other
     than `--mac-pascal').

`--longjmp-all-nonlocal-labels'
     Use `longjmp' for all nonlocal labels.

`--no-longjmp-all-nonlocal-labels'
     Use `longjmp' only for nonlocal labels in the main program
     (default).

`--nonlocal-exit'
     Allow non-local `Exit' statements (default in `--ucsd-pascal' and
     `--mac-pascal').

`--no-nonlocal-exit'
     Do not allow non-local `Exit' statements (default).

`--io-checking'
     Check I/O operations automatically (same as `{$I+}') (default).

`--no-io-checking'
     Do not check I/O operations automatically (same as `{$I-}').

`--pointer-checking-user-defined'
     Use user-defined procedure for validating pointers.

`--no-pointer-checking-user-defined'
     Do not use user-defined procedure for validating pointers
     (default).

`--pointer-checking'
     Validate pointers before dereferencing.

`--no-pointer-checking'
     Do not validate pointers before dereferencing (default).

`--object-checking'
     Check for valid objects on virtual method calls (default).

`--no-object-checking'
     Do not check for valid objects on virtual method calls.

`--range-checking'
     Do automatic range checks') (default).

`--no-range-checking'
     Do not do automatic range checks (same as `{$R-}').

`--range-and-object-checking'
     Same as `--range-checking --object-checking', same as `{$R+}'.

`--no-range-and-object-checking'
     Same as `--no-range-checking --no-object-checking', same as
     `{$R-}'.

`--case-value-checking'
     Cause a runtime error if a `case' matches no branch (default in
     ISO Pascal modes).

`--no-case-value-checking'
     Do not cause a runtime error if a `case' matches no branch
     (default).

`--stack-checking'
     Enable stack checking (same as `{$S+}').

`--no-stack-checking'
     Disable stack checking (same as `{$S-} (default)').

`--read-base-specifier'
     In read statements, allow input base specifier `n#' (default).

`--no-read-base-specifier'
     In read statements, do not allow input base specifier `n#'
     (default in ISO 7185 Pascal).

`--read-hex'
     In read statements, allow hexadecimal input with `$' (default).

`--no-read-hex'
     In read statements, do not allow hexadecimal input with `$'
     (default in ISO 7185 Pascal).

`--read-white-space'
     In read statements, require whitespace after numbers.

`--no-read-white-space'
     In read statements, do not require whitespace after numbers
     (default).

`--write-clip-strings'
     In write statements, truncate strings exceeding their field width
     (`Write (SomeLongString : 3)').

`--no-write-clip-strings'
     Do not truncate strings exceeding their field width.

`--write-real-blank'
     Output a blank in front of positive reals in exponential form
     (default).

`--no-write-real-blank'
     Do not output a blank in front of positive reals in exponential
     form.

`--write-capital-exponent'
     Write real exponents with a capital `E'.

`--no-write-capital-exponent'
     Write real exponents with a lowercase `e'.

`--transparent-file-names'
     Derive external file names from variable names.

`--no-transparent-file-names'
     Do not derive external file names from variable names (default).

`--field-widths'
     Optional colon-separated list of default field widths for Integer,
     Real, Boolean, LongInt, LongReal.

`--no-field-widths'
     Reset the default field widths.

`--pedantic'
     Reject everything not allowed in some dialect, e.g. redefinition
     of its keywords.

`--no-pedantic'
     Don't give pedantic warnings.

`--typed-address'
     Make the result of the address operator typed (same as `{$T+}',
     default).

`--no-typed-address'
     Make the result of the address operator an untyped pointer (same
     as `{$T-}').

`--enable-keyword'
     Enable a keyword, independently of dialect defaults.

`--disable-keyword'
     Disable a keyword, independently of dialect defaults.

`--implicit-result'
     Enable implicit `Result' for functions (default only in
     `--delphi').

`--no-implicit-result'
     Disable implicit `Result' for functions.

`--enable-predefined-identifier'
     Enable a predefined identifier, independently of dialect defaults.

`--disable-predefined-identifier'
     Disable a predefined identifier, independently of dialect defaults.

`--assertions'
     Enable assertion checking (default).

`--no-assertions'
     Disable assertion checking.

`--setlimit'
     Define the range for `set of Integer' etc..

`--gpc-main'
     External name for the program's entry point (default: `main').

`--propagate-units'
     Automatically re-export all imported declarations.

`--no-propagate-units'
     Do not automatically re-export all imported declarations.

`--interface-only'
     Compile only the interface part of a unit/module and exit (creates
     `.gpi' file, no `.o' file.

`--implementation-only'
     Do not produce a GPI file; only compile the implementation part.

`--executable-file-name'
     Name for the output file, if specified; otherwise derive from main
     source file name.

`--unit-path'
     Directories where to look for unit/module sources.

`--no-unit-path'
     Forget about directories where to look for unit/module sources.

`--object-path'
     Directories where to look for additional object (and source) files.

`--no-object-path'
     Forget about directories where to look for additional object (and
     source) files.

`--executable-path'
     Path where to create the executable file.

`--no-executable-path'
     Create the executable file in the directory where the main source
     is (default).

`--unit-destination-path'
     Path where to create object and GPI files of Pascal units.

`--no-unit-destination-path'
     Create object and GPI files of Pascal units in the current
     directory (default).

`--object-destination-path'
     Path where to create additional object files (e.g. of C files, not
     Pascal units).

`--no-object-destination-path'
     Create additional object files (e.g. of C files, not Pascal units)
     in the current directory (default).

`--disable-default-paths'
     Do not add a default path to the unit and object path.

`--gpi-destination-path'
     (Internal switch used for automake).

`--uses'
     Add an implicit `uses' clause.

`--init-modules'
     Initialize the named modules in addition to those imported
     regularly; kind of a kludge.

`--cidefine'
     Define a case-insensitive macro.

`--csdefine'
     Define a case-sensitive macro.

`--big-endian'
     Tell GPC that the system is big-endian (for those targets where it
     can vary).

`--little-endian'
     Tell GPC that the system is little-endian (for those targets where
     it can vary).

`--print-needed-options'
     Print the needed options.

`-Wwarnings'
     Enable warnings (same as `{$W+}').

`-Wno-warnings'
     Disable all warnings (same as `{$W-}').

`-Widentifier-case-local'
     Warn about an identifier written with varying case within one
     program/module/unit.

`-Wno-identifier-case-local'
     Same as `-Wno-identifier-case'.

`-Widentifier-case'
     Warn about an identifier written with varying case.

`-Wno-identifier-case'
     Do not warn about an identifier written with varying case
     (default).

`-Winterface-file-name'
     Warn when a unit/module interface differs from the file name.

`-Wno-interface-file-name'
     Do not warn when a unit/module interface differs from the file
     name (default).

`--methods-always-virtual'
     Make all methods virtual (default in `--mac-pascal').

`--no-methods-always-virtual'
     Do not make all methods virtual (default).

`-Wimplicit-abstract'
     Warn when an object type not declared `abstract' contains an
     abstract method (default).

`-Wno-implicit-abstract'
     Do not warn when an object type not `declared' abstract contains
     an abstract method.

`-Winherited-abstract'
     Warn when an abstract object type inherits from a non-abstract one
     (default).

`-Wno-inherited-abstract'
     Do not warn when an abstract object type inherits from a
     non-abstract one.

`-Wobject-assignment'
     Warn when when assigning objects or declaring them as value
     parameters or function results (default).

`-Wno-object-assignment'
     Do not warn when assigning objects or declaring them as value
     parameters or function results (default in `--borland-pascal').

`-Wimplicit-io'
     Warn when `Input' or `Output' are used implicitly.

`-Wno-implicit-io'
     Do not warn when `Input' or `Output' are used implicitly (default).

`-Wfloat-equal'
     Warn about `=' and `<>' comparisons of real numbers.

`-Wno-float-equal'
     Do not warn about `=' and `<>' comparisons of real numbers.

`-Wtyped-const'
     Warn about misuse of typed constants as initialized variables
     (default).

`-Wno-typed-const'
     Do not warn about misuse of typed constants as initialized
     variables.

`-Wnear-far'
     Warn about use of useless `near' or `far' directives (default).

`-Wno-near-far'
     Do not warn about use of useless `near' or `far' directives.

`-Wunderscore'
     Warn about double/leading/trailing underscores in identifiers.

`-Wno-underscore'
     Do not warn about double/leading/trailing underscores in
     identifiers.

`-Wsemicolon'
     Warn about a semicolon after `then', `else' or `do' (default).

`-Wno-semicolon'
     Do not warn about a semicolon after `then', `else' or `do'.

`-Wlocal-external'
     Warn about local `external' declarations.

`-Wno-local-external'
     Do not warn about local `external' declarations.

`-Wdynamic-arrays'
     Warn about arrays whose size is determined at run time (including
     array slices).

`-Wno-dynamic-arrays'
     Do not warn about arrays whose size is determined at run time
     (including array slices).

`-Wmixed-comments'
     Warn about mixed comments like `{ ... *)'.

`-Wno-mixed-comments'
     Do not warn about mixed comments.

`-Wnested-comments'
     Warn about nested comments like `{ { } }'.

`-Wno-nested-comments'
     Do not warn about nested comments.

`--classic-pascal-level-0'
     Reject conformant arrays and anything besides ISO 7185 Pascal.

`--standard-pascal-level-0'
     Synonym for `--classic-pascal-level-0'.

`--classic-pascal'
     Reject anything besides ISO 7185 Pascal.

`--standard-pascal'
     Synonym for `--classic-pascal'.

`--extended-pascal'
     Reject anything besides ISO 10206 Extended Pascal.

`--object-pascal'
     Reject anything besides (the implemented parts of) ANSI draft
     Object Pascal.

`--ucsd-pascal'
     Try to emulate UCSD Pascal.

`--borland-pascal'
     Try to emulate Borland Pascal, version 7.0.

`--delphi'
     Try to emulate Borland Pascal, version 7.0, with some Delphi
     extensions.

`--pascal-sc'
     Be strict about the implemented Pascal-SC extensions.

`--vax-pascal'
     Support (a few features of) VAX Pascal.

`--sun-pascal'
     Support (a few features of) Sun Pascal.

`--mac-pascal'
     Support (some features of) traditional Macintosh Pascal compilers.

`--gnu-pascal'
     Undo the effect of previous dialect options, allow all features
     again.


File: gpc-hr.info,  Node: GPC Options,  Prev: GPC Command Line Options,  Up: Invoking GPC

5.2 Najčešće korištene opcije GPC-a
===================================

Kao najjednostavniji primjer, pozivanje

     gpc foo.pas

   kaže GPC-u da prevede izvorni kod u datoteci `foo.pas' i da proizvede
izvršnu (engl. executable) datoteku sa podrazumijevanim (engl. default)
imenom, koje je `foo.exe' na EMX platformi, `a.exe' na CygWin, ujedno
`a.out' i `a.exe' na DJGPP, te `a.out' na većini ostalih platformi.

   Korisnik blizak s BP-om (Borland Pascalom) može uočiti da je
neophodno dati datoteci ekstenziju (sufiks) `.pas': GPC je zajedničko
sučelje (engl.  interface) za Pascal prevodilac, ali i za C, ObjC, i
C++ prevodilac, asembler, linker; a možda i za Adu i Fortran
prevodilac. Prema ekstenziji vaše izvorne datoteke GPC određuje koji
prevodilac treba pokrenuti. GPC prepoznaje Pascal programe prema
ekstenziji `.pas', `.p', `.pp' ili `.dpr'. GPC također prihvaća izvorne
kodove u drugim jezicima (npr.  `.c' for C) i poziva odgovarajuće
prevoditelje za njih. Datoteke s ekstenzijom `.o' ili bez ijedne
poznate se smatraju objektnim datotekama ili bibliotekama funkcija
(engl. library) koje treba povezati (engl. link).

   Još jedan primjer:

     gpc -O2 -Wall --executable-file-name --automake --unit-path=units foo.pas

   Ovo će prevesti izvornu datoteku `foo.pas' u u izvršnu datoteku imena
`foo' (`--executable-file-name') sa relativno dobrom optimizacijom
(`-O2'), uz upozorenja o potencijalnim problemima `-Wall'. Ako program
koristi jedinice (UNIT) ili importira module, njih će prevodilac
potražiti u direktoriju imena `units' (`--unit-path') i automatski
prevesti i povezati (`--automake').

   Slijedeća tablica navodi najčešće korištene opcije GPC-a.

`--automake'
     Provjerava da li korišteni moduli/jedinice moraju biti ponovno
     prevedeni i vrši ponovno prevođenje ako je to neophodno.

`--unit-path=DIR[:DIR...]'
     Traži jedinice (engl. i Pascal UNIT) i objektne datoteke u danim
     direktorijima.

`--object-path=DIR[:DIR...]'
     Traži objektne datoteke u navedenim direktorijima.

`--unit-destination-path=DIR'
     Smješta prevedene jedinice (GPI i objektne datoteke) u direktorij
     DIR.  Podrazumna (engl. default) vrijednost u slučaju
     izostavljanja opcije je trenutni direktorij.

`--object-destination-path=DIR'
     Smješta prevedene objektne datoteke (npr. od C datoteka, ali ne od
     Pascal jedinica) u direktorij DIR. Podrazumijevana (default)
     vrijednost je direktorij dan sa `--unit-destination-path'.

`--executable-path=DIR'
     Smješta proizvedenu izvršnu datoteku u direktorij DIR. Podrazumna
     vrijednost je direktorij u kojem se nalazi glavna izvorna datoteka.

`-o FILE'
     Smjesti izlaz u datoteku FILE. Ovo vrijedi bez obzira na tip izlaza
     koji je proizveden, bio on izvršna datoteka, objektna datoteka,
     asemblerski listing itd.

     Kako samo jedna izlazna datoteka može biti navedena, nema smisla
     koristiti `-o' opciju kad se prevodi više od jedne ulazne
     datoteke, osim ako se proizvodi izvršna datoteka kao izlaz.

`--executable-file-name[=NAME]'
     Proizvodi ime izvršne datoteke iz imena izvorne datoteke, ili
     koristi NAME kao ime izvršne datoteke. Razlika u odnosu na `-o'
     opciju je da `--executable-file-name' uzima u obzir
     `--executable-path', dok `-o' to ne čini i prihvaća ime datoteke
     koje uključuje direktorij.  Dalje, `--executable-file-name' se
     odnosi samo na izvršne datoteke, ne na ostale izabrane oblike
     izlaznih datoteka.

`-LDIR'
     Traži biblioteke funkcija (eng. libraries) u direktoriju DIR. Može
     se navesti više puta.

`-IDIR'
     Traži include (uključne) datoteke u direktoriju DIR. Može se
     navesti više puta.

`-lLIBRARY'
     Potraži biblioteku funkcija LIBRARY kod povezivanja. Ova se opcija
     mora nalaziti u komandnoj liniji _iza_ svih izvornih ili objektnih
     datoteka te drugih biblioteka koje referenciraju LIBRARY.

`-O[N]'
     Izaberi nivo optimizacije. Bez optimizacije (ili `-O0' što je
     podrazumna -default- vrijednost), cilj prevoditelja je da smanji
     vrijeme prevođenja i da proces otkrivanja pogrešaka (engl.
     debugging) da očekivane rezultate.  Naredbe su neovisne: ako
     zaustavite program prekidnom točkom (engl. breakpoint) između
     naredbi, možete dodijeliti novu vrijednost nekoj varijabli ili
     promijeniti programski brojač na bilo koju drugu naredbu u istoj
     rutini i dobiti točno rezultate koje očekujete od izvornog koda.

     S optimizacijom, prevodilac nastoji reducirati veličinu izvršnog
     koda i trajanje izvršavanja. Što veća vrijednost N, više će se
     optimizacija izvesti, ali će prevođenje trajati dulje.

     Ako koristite više `-O' opcija, sa ili bez N, zadnja opcija je ona
     koja je važeća.

`-g'
     Proizvedi informacije za debugging (ispravljanje progrešaka)
     prikladne za `gdb'. Za razliku od nekih drugih prevoditelja, GNU
     Pascal dozvoljava da koristite `-g' sa `-O'. Prečice poduzete od
     strane optimiziranog koda mogu povremeno proizvesti iznenađujuće
     rezultate: neke varijable koje ste deklarirali mogu uopće ne
     postojati; tijek programa može se skokovito premjestiti gdje ga
     niste očekivali; neke naredbe se mogu ne izvršiti jer izračunavaju
     konstantnu vrijednost ili su njihove vrijednosti već bile pri
     ruci; neke se naredbe mogu izvršiti na drugim mjestima jer su
     pomaknute izvan petlji. Međutim, pokazuje se mogućim debuggirati
     optimizirani izlaz.  Ovo čini razumnim koristiti optimizer za
     programe još i u testnoj fazi.

`-s'
     Ukloni sve simbol tablice i relokacijske informacije iz izvršne
     datoteke.  Primjedba: ovo nema utjecaja na performanse prevedene
     izvršne datoteke.

`-Wall'
     Daj upozorenja za izvjestan broj konstrukata koji nisu po sebi
     pogrešni ali su rizični ili sugeriraj da je možda učinjena
     pogreška u kodiranju. Postoje dodatne opcije upozorenja koje nisu
     uključene sa `-Wall', vidi GCC opcije upozorenja (engl. warnings)
     (*note Options to Request or Suppress Warnings: (gcc)Warning
     Options.), dok `-Wall' samo upozorava na takve konstrukte koje je
     lako izbjeći u programima. Dakle, savjetujemo koristiti `-Wall' na
     većini programa.

     Primijetimo da neka upozorenja (npr. ona o neinicijaliziranim
     varijablama) nisu nikad dana ako se ne prevodi s optimizacijom
     (vidi gore), jer prevodilac inače ne analizira uzorke korištenja
     varijabli.

`-Werror'
     Pretvara sva upozorenja u pogreške.

`-S'
     Zaustavi se nakon prevođenja; ne asembliraj. Izlaz je u obliku
     asemblerskog koda za svaku izvornu datoteku. Podrazumno (default),
     ime asemblerske datoteke za datu izvornu datoteku nastaje zamjenom
     ekstenzije sa `.s'.

`-c'
     Prevedi i asembliraj izvornu datoteku, ali ne povezuj. Izlaz je u
     obliku objektne datoteke za svaku izvornu datoteku. Podrazumno,
     ukoliko se drugačije ne navede, ime objektne datoteke za izvornu
     datoteku nastaje zamjenom ekstenzije izvorne datoteke sa `.o'.

`-static'
     Na sistemima koji podržavaju dinamičko povezivanje, ovo zabranjuje
     povezivanje sa dijeljenim bibliotekama (engl. shared libraries),
     tj. traži statičko povezivanje. Na ostalim sistemima ova opcija
     nema efekta.

`-DMACRO[=DEF]'
     Definiraj makro i uvjetni simbol MACRO kao DEF (ili kao `1' ako je
     DEF izostavljen).

`-b MACHINE'
     Parametar MACHINE specificira ciljni stroj za prevođenje. Ovo je
     korisno ako je GNU Pascal instaliran kao prevodilac za drugu
     platformu (engl. cross- compiler).

`-v'
     Ispiši (na tok pogreški) naredbe izvršavane da se pokrenu pojedini
     stupnjevi prevođenja. Također ispiši broj verzije pogonskog
     programa prevoditelja, preprocesora i samog prevoditelja.

`--classic-pascal-level-0'
`--classic-pascal'
`--extended-pascal'
`--object-pascal'
`--ucsd-pascal'
`--borland-pascal'
`--pascal-sc'
     GNU Pascal podržava svojstva nekoliko različitih Pascal standarda
     i dijalekata.  Inicijalno, oni su svi omogućeni. Ovi prekidači
     upućuju GPC da ograniči sebe na svojstva specificiranog standarda;
     ne omogućuju bilo kakva dodatna svojstva. Upozorenja o nekim
     opasnim konstruktima koji bi bili legalni za specificirani
     dijalekt (npr. operacija dodjele vrijednosti tipiziranoj konstanti
     uz `--borland-pascal') se potiskuju.

     Inicijalno, GNU Pascal dozvoljava redefiniciju inekih ključnih
     riječi jezika. Svaki od ovih prekidača prouzročuje da GNU Pascal
     zabrani redefiniciju ključnih riječi specificiranog standarda.

     Ispravni ISO 7185 Pascal programi bi se trebali prevesti ispravno
     sa ili bez `--classic-pascal'. Međutim, bez ove opcije neka GNU
     proširenja i značajke drugih dijalekata Pascala su također
     podržane. Sa ovom opcijom, ta proširenja su odbijena.

     Ove opcije nisu tu s namjerom da budu korisne, one postoje samo da
     zadovolje pedantne koji bi inače tvrdili da GNU Pascal ne
     ispunjava ISO standard ili nije zaista kompatibilan sa Borland
     Pascalom, ili što već.  Mi preporučujemo, radije, da korisnici
     iskoriste prednosti ekstenzija GNU Pascala i zanemare ograničenja
     drugih prevodilaca.

`-pedantic-errors'
     Proizvedi greške radije nego upozorenja za kršenja prenosivosti
     koda (engl. portability). Za razliku od C-a, ovo _ne_ implicira
     `-pedantic' opciju, pa možete, na primjer, koristiti
     `-pedantic-errors' bez `-pedantic', ali sa `--extended-pascal'.

`--gpc-main=NAME'
     Imenuj ulaznu točku glavnog programa `NAME' umjesto `main' na
     nivou povezivača. Ovo je korisno npr. kad se radi s nekim C
     bibliotekama funkcija koje definiraju svoju vlastitu `main'
     funkciju i traže da se programska ulazna točka (engl. entry point)
     nazove drugačije.

     (Preferira se korištenje ove direktive prevodiocu u jedinici ili
     modulu koji se povezuje s tom čudnom C bibliotekom, radije nego da
     se direktiva daje u naredbenoj (komandnoj) liniji.)



File: gpc-hr.info,  Node: Programming,  Next: Borland Pascal,  Prev: Invoking GPC,  Up: Top

6 The Programmer's Guide to GPC
*******************************

*This chapter is still under development.*

   This chapter tells you how the source of a valid GNU Pascal program
should look like.  You can use it as tutorial about the GNU Pascal
language, but since the main goal is to document all special GPC
features, implementation-dependent stuff, etc., expect a steep learning
curve.

   This chapter does _not_ cover how to compile your programs and to
produce an executable - this is discussed above in *Note Invoking GPC::.

* Menu:

* Source Structures::    Programs, Units and Modules.
* Data Types::           Standard and non-standard data types.
* Operators::            Built-in and user-definable operators.
* Parameters::           Procedure And Function Parameters
* Pointer Arithmetics::  How pointer arithmetics works in Pascal.
* String Slice Access::  Accessing parts of strings (and other arrays)
* Type Casts::           Explicit and emulated type casting in GPC.
* OOP::                  How object-oriented programming is implemented.
* Compiler Directives::  Compiler Directives And The Preprocessor
* Library Routines::     Routines Built-in or in the Run Time System
* Other Languages::      How to share libraries with other languages.
* Notes for Debugging::  Problems and caveats when debugging GPC programs.
* I18N::                 How to use Internationalization in your programs
* Run Time System::      Pascal declarations for GPC's Run Time System library.
* GPC Units::            Units included with GPC


File: gpc-hr.info,  Node: Source Structures,  Next: Data Types,  Up: Programming

6.1 Source Structures
=====================

A source file accepted by GNU Pascal may contain up to one program,
zero or more ISO-style modules, and/or zero or more UCSD-style units.
Units and modules can be mixed in one project.

* Menu:

* The Program::             The Source Structure of Programs
* Label Declaration::
* Constant Declaration::
* Type Declaration::
* Variable Declaration::
* Subroutine Declaration::  Procedures, Functions and Operators
* Statements::              Loops and Conditional Statements
* Modules and Units::       Import Part and Module/Unit Concept

   One trivial example for a valid GPC source file follows. Note that
the code below may either be in one source file, or else the unit and
the program may be in separate source files.

     unit DemoUnit;

     interface

     procedure Hello;

     implementation

     procedure Hello;
     begin
       WriteLn ('Hello, world!')
     end;

     end.

     program UnitDemo;

     uses
       DemoUnit;

     begin
       Hello
     end.


File: gpc-hr.info,  Node: The Program,  Next: Label Declaration,  Up: Source Structures

6.1.1 The Source Structure of Programs
--------------------------------------

A generic GNU Pascal program looks like the following:

     program NAME (Input, Output);

     IMPORT_PART

     DECLARATION_PART

     begin
       STATEMENT_PART
     end.

   The `program' headline may be omitted in GPC, but a warning will be
given except in `--borland-pascal' mode.

   While the program parameters (usually `Input', `Output') are
obligatory in ISO Pascal if you want to use `ReadLn' and `WriteLn',
they are optional in GNU Pascal. GPC will warn about such missing
parameters in `--extended-pascal' mode. However if you give parameters
to the program headline, they work like ISO requires.

   The IMPORT_PART consists either of an ISO-style `import'
specification or a UCSD/Borland-style `uses' clause. While `import' is
intended to be used with interfaces exported by ISO 10206 Extended
Pascal modules, and `uses' is intended to be used with units, this is
not enforced. (See also *Note uses::, *Note import::.)

   The DECLARATION_PART consists of label, constant, type, variable or
subroutine declarations in free order. However, every identifier must
be declared before it is used. The only exception are type identifiers
pointing to another type identifier which may be declared below.

   The STATEMENT_PART consists of a sequence of statements.

   As an extension, GPC supports a "declaring statement" which can be
used in the statement part to declare variables (see *Note var::).


File: gpc-hr.info,  Node: Label Declaration,  Next: Constant Declaration,  Prev: The Program,  Up: Source Structures

6.1.2 Label Declaration
-----------------------

A label declaration has the following look:

     label
       LABEL_NAME, ..., LABEL;

   A label declaration part starts with the reserved word `label',
which contains a list of labels.

See also
--------

*Note label::, *Note goto::


File: gpc-hr.info,  Node: Constant Declaration,  Next: Type Declaration,  Prev: Label Declaration,  Up: Source Structures

6.1.3 Constant Declaration
--------------------------

A constant declaration has the following look:

     const
       CONSTANT_IDENTIFIER = CONSTANT_EXPRESSION;
       ...
       CONSTANT_IDENTIFIER = CONSTANT_EXPRESSION;

   A constant declaration part starts with the reserved word `const'.
It declares a CONSTANT_IDENTIFIER which is defined by
CONSTANT_EXPRESSION. This expression has to be evaluatable during
compilation time, i.e. it can include numbers, parentheses, predefined
operators, sets and type casts (the last, however, is a Borland
extension).  In ISO 7185 Pascal, CONSTANT_EXPRESSION must be a constant
or a set. All Pascal Dialects but ISO-Pascal allow the use of these
intrinsic functions in CONSTANT_EXPRESSION:

   *Note Abs::, *Note Round::, *Note Trunc::, *Note Chr::, *Note Ord::,
*Note Length::, *Note Pred::, *Note Succ::, *Note SizeOf::, *Note Odd::.

   In Borland Pascal, in the constant declaration part variables can be
declared as well, which are given an initial value. These variables are
called "typed constants". It is good style to avoid this use,
especially since Extended Pascal and GNU Pascal allow to initialize a
variable in variable declaration part or give a type a preset value on
declaration.

     const
       FiveFoo      = 5;
       StringFoo    = 'string constant';
       AlphabetSize = Ord ('Z') - Ord ('A') + 1;

     type
       PInteger     = ^Integer;     { Define a pointer to an Integer }

     const
       { Constant which holds a pointer to an Integer at address 1234 }
       AddressFoo   = PInteger (1234);

   * BP does not know initialized variables, only typed constants. Even
     worse, it allows them to be misused as variables, without even
     warning. GPC supports this (unwillingly ;-), and warns unless in
     `--borland-pascal' mode.

     An example of a typed constant:

          const
            i: Integer = 0;

     If you want to use it as a constant only, that's perfectly fine.
     However, if you modify `i', we suggest to translate the
     declaration to an initialized variable. The EP syntax is:

          var
            i: Integer value 0;

     GPC supports this as well as the following mixture of dialects:

          var
            i: Integer = 0;

     Furthermore, you can also assign initialization values to types:

          program InitTypeDemo;

          type
            MyInteger = Integer value 42;

          var
            i: MyInteger;

          begin
            WriteLn (i)
          end.

     Here, all variables of type MyInteger are automatically initialized
     to 42 when created.

   * Arrays initializers look like this in BP:

          program BPArrayInitDemo;

          const
            MyStringsCount = 5;

          type
            Ident = String [20];

          const
            MyStrings: array [1 .. MyStringsCount] of Ident =
              ('export', 'implementation', 'import',
               'interface', 'module');

          begin
          end.

     And the following way in EP:

          program EPArrayInitDemo;

          const
            MyStringsCount = 5;

          type
            Ident = String (20);

          var
            MyStrings: array [1 .. MyStringsCount] of Ident value
              [1: 'export'; 2: 'implementation'; 3: 'import';
               4: 'interface'; 5: 'module'];

          begin
          end.

     There seem to be pros and cons to each style. GPC supports both as
     well as just about any thinkable mixture of them.

     Some folks don't like having to specify an index since it requires
     renumbering if you want to add a new item to the middle. However,
     if you index by an enumerated type, you might be able to avoid
     major renumbering by hand.


See also
--------

*Note Subroutine Parameter List Declaration::


File: gpc-hr.info,  Node: Type Declaration,  Next: Variable Declaration,  Prev: Constant Declaration,  Up: Source Structures

6.1.4 Type Declaration
----------------------

A type declaration looks like this:

     type
       TYPE_IDENTIFIER = TYPE_DEFINITION;
       ...
       TYPE_IDENTIFIER = TYPE_DEFINITION;
   or, with preset content:
     type
       TYPE_IDENTIFIER = TYPE_DEFINITION value CONSTANT_EXPRESSION;
       ...
       TYPE_IDENTIFIER = TYPE_DEFINITION value CONSTANT_EXPRESSION;

   A type declaration part begins with the reserved word `type'.  It
declares a TYPE_IDENTIFIER which is defined by TYPE_DEFINITION.  A type
definition either can be an array, a record, a schema, a set, an
object, a subrange, an enumerated type, a pointer to another
type_identifier or simply another type_identifier which is to alias.
If a schema type is to be declared, TYPE_IDENTIFIER is followed by a
discriminant enclosed in parentheses:

     TYPE_IDENTIFIER (DISCRIMINANT) = SCHEMA_TYPE_DEFINITION;

   If `value' is specified, followed by a constant satisfying the type
definition, every variable of this type is initialized with
CONSTANT_EXPRESSION, unless it is initialized by `value' itself.  The
reserved word `value' can be replaced by `=', however `value' is not
allowed in ISO-Pascal and Borland Pascal, and the replacement by `=' is
not allowed in Extended Pascal.

Type declaration example
------------------------

     type
       { This side is the }     { That side is the }
       { type declaration }     { type definition  }

       Arrayfoo            = array [0 .. 9] of Integer;  { array definition }
       Recordfoo           = record                      { record definition }
                               Bar: Integer;
                             end;

            { schema def with discriminants ``x, y: Integer'' }
       SchemaFoo (x, y: Integer) = array [x .. y] of Integer;
       CharSetFoo          = set of Char;              { Def of a set }
       ObjectFoo           = object                    { Def of an object }
                               procedure DoAction;
                               constructor Init;
                               destructor Done;
                             end;
       SubrangeFoo         = -123..456;                { subrange def }

       EnumeratedFoo       = (Pope,John,the,Second);   { enum type def }
            { Def of a pointer to another type identifier }
       PInteger            = ^arrayfoo;
            { Def of an alias name for another type identifier }
       IdentityFoo         = Integer;
            { Def of an integer which was initialized by 123 }
       InitializedFoo      = Integer value 123;

See also
--------

*Note Type Definition::, *Note Data Types::, *Note Variable
Declaration::


File: gpc-hr.info,  Node: Variable Declaration,  Next: Subroutine Declaration,  Prev: Type Declaration,  Up: Source Structures

6.1.5 Variable Declaration
--------------------------

A variable declaration looks like this:

     var
       VAR_IDENTIFIER: TYPE_IDENTIFIER;
       ...
       VAR_IDENTIFIER: TYPE_IDENTIFIER;
   or
     var
       VAR_IDENTIFIER: TYPE_DEFINITION;
       ...
       VAR_IDENTIFIER: TYPE_DEFINITION;
   and with initializing value:
     var
       VAR_IDENTIFIER: TYPE_IDENTIFIER value CONSTANT_EXPRESSION;
       ...
       VAR_IDENTIFIER: TYPE_IDENTIFIER value CONSTANT_EXPRESSION;
   or
     var
       VAR_IDENTIFIER: TYPE_DEFINITION value CONSTANT_EXPRESSION;
       ...
       VAR_IDENTIFIER: TYPE_DEFINITION value CONSTANT_EXPRESSION;

   A variable declaration part begins with the reserved word `var'.  It
declares a VAR_IDENTIFIER whose type either can be specified by a type
identifier, or by a type definion which either can be an array, a
record, a set, a subrange, an enumerated type or a pointer to an type
identifier.  If `value' is specified followed by a constant expression
satisfying the specified type, the variable declared is initialized with
CONSTANT_EXPRESSION.  The reserved word `value' can be replaced by `=',
however `value' is not allowed in ISO-Pascal and Borland Pascal, and the
replacement by `=' is not allowed in Extended Pascal.

See also
--------

*Note Type Definition::, *Note Type Declaration::, *Note Data Types::,
*Note The Declaring Statement::, *Note Subroutine Parameter List
Declaration::


File: gpc-hr.info,  Node: Subroutine Declaration,  Next: Statements,  Prev: Variable Declaration,  Up: Source Structures

6.1.6 Subroutine Declaration
----------------------------

* Menu:

* The Procedure::
* The Function::
* The Operator::
* Subroutine Parameter List Declaration::


File: gpc-hr.info,  Node: The Procedure,  Next: The Function,  Up: Subroutine Declaration

6.1.6.1 The Procedure
.....................

     procedure PROCEDURE_IDENTIFIER;
     DECLARATION_PART
     begin
       STATEMENT_PART
     end;
or with a parameter list:
     procedure PROCEDURE_IDENTIFIER (PARAMETER_LIST);
     DECLARATION_PART
     begin
       STATEMENT_PART
     end;

   A procedure is quite like a sub-program: The DECLARATION_PART
consists of label, constant, type, variable or subroutine declarations
in free order. The STATEMENT_PART consists of a sequence of statements.
If PARAMETER_LIST is specified, parameters can be passed to the
procedure and can be used in STATEMENT_PART. A recursive procedure call
is allowed.

See also
--------

*Note The Function::, *Note Subroutine Parameter List Declaration::


File: gpc-hr.info,  Node: The Function,  Next: The Operator,  Prev: The Procedure,  Up: Subroutine Declaration

6.1.6.2 The Function
....................

     function FUNCTION_IDENTIFIER: FUNCTION_RESULT_TYPE;
     DECLARATION_PART
     begin
       STATEMENT_PART
     end;
or with a parameter list:
     function FUNCTION_IDENTIFIER (PARAMETER_LIST): RESULT_TYPE;
     DECLARATION_PART
     begin
       STATEMENT_PART
     end;

   A function is a subroutine which has a return value of type
FUNCTION_RESULT_TYPE. It is structured like the program: the
DECLARATION_PART consists of label, constant, type, variable or
subroutine declarations in free order. The STATEMENT_PART consists of a
sequence of statements. If PARAMETER_LIST is specified, parameters can
be passed to the function and can be used in STATEMENT_PART. The result
is set via an assignment:
     FUNCTION_IDENTIFIER := EXPRESSION
   Recursive function calls are allowed. Concerning the result type,
ISO 7185 Pascal and Borland Pascal only allow the intrinsic types,
subranges, enumerated types and pointer types to be returned. In
Extended Pascal, FUNCTION_RESULT_TYPE can be every assignable type.  Of
course, there are no type restrictions in GNU Pascal as well.  If
extended syntax is switched on, functions can be called like procedures
via procedure call statement.

See also
--------

*Note The Procedure::, *Note Subroutine Parameter List Declaration::,
*Note Data Types::


File: gpc-hr.info,  Node: The Operator,  Next: Subroutine Parameter List Declaration,  Prev: The Function,  Up: Subroutine Declaration

6.1.6.3 The Operator
....................

GNU Pascal allows to define operators which can be used the infix style
in expressions. For a more detailed description, see *Note Operators::


File: gpc-hr.info,  Node: Subroutine Parameter List Declaration,  Prev: The Operator,  Up: Subroutine Declaration

6.1.6.4 Subroutine Parameter List Declaration
.............................................

     PARAMETER; ...; PARAMETER

   Each parameter can start with a prefix (see below) describing how
the parameters are passed, followed by a comma seperated list of one or
more PARAMETER_IDENTIFIERS and an optional PARAMETER_TYPE.

     procedure DoIt (var x, y, z: OneType; a, b: AnotherType; var q);

   To understand parameter passing, first some definitions.

actual parameter
     the parameter passed in to the routine.

formal parameter
     the parameter as used inside the procedure.

by value
     the value of the actual parameter is copied on to the stack.

by reference
     the address of the actual parameter is copied on to the stack.

L-value
     (left hand of a `:=' statement) something that can be assigned
     to (not a constant, or const or protected variable or other
     immutable item).

R-value
     (right hand of a `:=' statement) anything you can get the   value
     of (could be a constant, an expression, a variable (whether
     const or protected or not) or just about anything.

addressable
     something you can get the address of (not a field of a packed
     structure or a variable with `attribute (register)' (GPC
     extension)).

aliasing
     accessing memory via two different names (e.g. a global variable
     passed by reference to a procedure can be accessed either as the
     global variable or the formal paramater). Generally this is very
     bad practice.

   Technical note: Parameters are not always passed on the stack, they
may also be passed in registers, especially on RISC machines.

   The prefix defines how a variable is passed on the stack and how you
can access the FORMAL_PARAMETER inside the procedure.  The prefix can
be one of:

nothing
          procedure DoIt (x: SOMETYPE);

     Technical: The actual parameter is passed by value or reference,
     but if passed by reference, it is then copied to a local copy on
     the stack. Aliasing has no effect on x.

     What it means: you can modify `x' inside the routine, but your
     changes will not affect the actual parameter (and vice versa). The
     actual parameter can be a constant or other immutable object, or a
     protected or const variable.

protected
          procedure DoIt (protected x: SOMETYPE);

     Technical: The actual parameter is passed by value or reference,
     but if passed by reference, it is then copied to a local copy on
     the stack. Aliasing has no effect on x. `protected' is a Extended
     Pascal extension.

     What it means: if you modify the actual parameter, this will not
     affect `x' inside the routine. The actual parameter can be a
     constant or other immutable object, or a protected or const
     variable. You are forbidden from modifying x inside the routine.

var
          procedure DoIt (var x: SOMETYPE);

     Technical: The actual parameter is passed by reference.  Aliasing
     will definitely change `x'.

     What it means: modifications to `x' inside the routine will change
     the actual parameter passed in. The actual parameter must be an
     addressable L-value (ie, it must be something you can take the
     address of and assign to).

     A parameter of this kind is called variable parameter and
     internally corresponds to an L-value pointer (to the specified
     type identifier if any). This declaration is necessary if the
     parameter is to be modified within the routine and to hold its
     value still after return.

const
          procedure DoIt (const x: SOMETYPE);

     Technical: The actual parameter is passed by value or reference.
     The compiler will make a copy of the actual parameter to have
     something it can address if the actual parameter is not
     addressable.  You are forbidden from modifying `x' inside the
     routine, and therefore you cannot modify the actual parameter.
     Aliasing may or may not change `x'. `const' is a Borland Pascal
     extension.

     What it means: You can pass any R-value. You cannot modify `x'
     inside the routine. If you change the actual parameter while inside
     the routine, `x' will have an undefined value.

protected var
          procedure DoIt (protected var x: SOMETYPE);

     Technical: The actual parameter is passed by reference. The
     compiler will never make a copy of the actual parameter. You are
     forbidden from modifying `x' inside the routine, and therefore you
     cannot modify the actual parameter. Aliasing will definitely change
     `x'.

     What it means: You can pass anything addressable. You cannot modify
     `x' inside the routine. If you change the actual parameter while
     inside the routine, `x' will change as well.

     In GPC, the `protected var' mode guarantees that the parameter is
     always passed by reference, making it the correct choice for
     calling C routines with `const' pointer parameters.


   If you omit the formal parameter type specification, then any type
may be passed to that parameter. Generally this is a bad idea, but
occasionally it can be useful, especially for low level code.

   As an Extended Pascal extension, you can also declare procedural
parameters directly:
     procedure PARAMETER_IDENTIFIER
   or:
     function PARAMETER_IDENTIFIER: PARAMETER_IDENTIFIER_RESULT_TYPE

   Example for parameter lists:
     program ParameterDemo;

     procedure Foo (var Bar; var Baz: Integer; const Fred: Integer);

       procedure Glork1 (function Foo: Integer; procedure Bar (Baz: Integer));
       begin
         Bar (Foo)
       end;

     begin
       Baz := Integer (Bar) + Fred
     end;

     var
       a, b, c: Integer;

     begin
       Foo (a, b, c)
     end.

See also
--------

*Note Data Types::, *Note var::, *Note const::, *Note protected::


File: gpc-hr.info,  Node: Statements,  Next: Modules and Units,  Prev: Subroutine Declaration,  Up: Source Structures

6.1.7 Statements
----------------

* Menu:

* Assignment::
* begin end Compound Statement::
* if Statement::
* case Statement::
* for Statement::
* while Statement::
* repeat Statement::
* asm Inline::
* with Statement::
* goto Statement::
* Procedure Call::
* The Declaring Statement::
* Loop Control Statements::


File: gpc-hr.info,  Node: Assignment,  Next: begin end Compound Statement,  Up: Statements

6.1.7.1 Assignment
..................

The way an assignment looks like:
     L-VALUE := EXPRESSION;

   This statement assigns any valid expression to L-VALUE. Make sure
that the result of EXPRESSION is compatible with L-VALUE, otherwise an
compilation error is reported. The `:=' is called assignment operator.
As long as L-VALUE and EXPRESSION are type compatible, they are
assignment compatible for _any definable type_ as well.


File: gpc-hr.info,  Node: begin end Compound Statement,  Next: if Statement,  Prev: Assignment,  Up: Statements

6.1.7.2 begin end Compound Statement
....................................

It looks like that:
     begin
       STATEMENT;
       STATEMENT;
       ...
       STATEMENT
     end

   This statement joins several STATEMENTS together into one compound
statement which is treated as a single statement by the compiler. The
finishing semicolon before `end' can be left out.


File: gpc-hr.info,  Node: if Statement,  Next: case Statement,  Prev: begin end Compound Statement,  Up: Statements

6.1.7.3 if Statement
....................

This statement has the following look:
     if BOOLEAN_EXPRESSION then
       STATEMENT
   or with an alternative statement:
     if BOOLEAN_EXPRESSION then
       STATEMENT1
     else
       STATEMENT2

   The `if' ... `then' statement consists of a boolean expression and a
STATEMENT, which is conditionally executed if the evaluation of
BOOLEAN_EXPRESSION yields true.

   If `if' ... `then' ... `else' is concerned, STATEMENT1 is executed
depending on BOOLEAN_EXPRESSION being true, otherwise STATEMENT2 is
executed alternatively. Note: the statement before else _must not_
finish with a semicolon.


File: gpc-hr.info,  Node: case Statement,  Next: for Statement,  Prev: if Statement,  Up: Statements

6.1.7.4 case Statement
......................

     case EXPRESSION of
       SELECTOR: STATEMENT;
       ...
       SELECTOR: STATEMENT;
     end
or, with alternative statement sequence:
     case ORDINAL_EXPRESSION of
       SELECTOR: STATEMENT;
       ...
       SELECTOR: STATEMENT;
     otherwise                   { ``else'' instead of ``otherwise'' allowed }
       STATEMENT;
       ...
       STATEMENT;
     end
   or, as part of the invariant `record' type definition:
     type
       foo = record
         FIELD_DECLARATIONS
       case bar: VARIANT_TYPE of
         SELECTOR: (FIELD_DECLARATIONS);
         SELECTOR: (FIELD_DECLARATIONS);
         ...
       end;
   or, without a variant selector field,
     type
       foo = record
         FIELD_DECLARATIONS
       case VARIANT_TYPE of
         SELECTOR: (FIELD_DECLARATIONS);
         SELECTOR: (FIELD_DECLARATIONS);
         ...
       end;

   The `case' statement compares the value of ORDINAL_EXPRESSION to
each SELECTOR, which can be a constant, a subrange, or a list of them
separated by commas, being compatible with the result of
ORDINAL_EXPRESSION.  Note: duplicate selectors or range crossing is not
allowed unless {$borland-pascal} is specified. In case of equality the
corresponding statement is executed. If `otherwise' is specified and no
appropriate selector matched the expression, the series of statements
following `otherwise' is executed. As a synonym for `otherwise', `else'
can be used. The semicolon before `otherwise' is optional.

   @@ ????  The expression _must_ match one of the selectors in order
to continue, unless an alternative statement series is specified.

   For `case' in a variant record type definition, see *Note Record
Types::.

See also
--------

*Note if Statement::


File: gpc-hr.info,  Node: for Statement,  Next: while Statement,  Prev: case Statement,  Up: Statements

6.1.7.5 for Statement
.....................

For ordinal index variables:
     for ORDINAL_VARIABLE := INITIAL_VALUE to FINAL_VALUE do
       STATEMENT
   or
     for ORDINAL_VARIABLE := INITIAL_VALUE downto FINAL_VALUE do
       STATEMENT

   For sets:
     for SET_ELEMENT_TYPE_VARIABLE in SOME_SET do
       STATEMENT

   For pointer index variables:
     for POINTER_VARIABLE := INITIAL_ADDRESS to FINAL_ADDRESS do
       STATEMENT
   or
     for POINTER_VARIABLE := INITIAL_ADDRESS downto FINAL_ADDRESS do
       STATEMENT

   The FOR statement is a control statement where an index variable
assumes every value of a certain range and for every value the index
variable assumes STATEMENT is executed. The range can be specified by
two bounds (which must be of the same type as the index variable, i.e.
ordinal or pointers) or by a set.

   For ordinal index variables:
   - If `to' is specified, the index counter is increased by one as
     long as INITIAL_VALUE is less or equal to FINAL VALUE,

   - if `downto' is specified, it is decreased by one as long as
     INITIAL_VALUE is greater or equal to FINAL_VALUE.

   For pointer index variables:
   - If `to' is specified, the index counter is increased by the size
     of the type the index variable points to (if it is a typed
     pointer, otherwise by one if it is typeless) as long as
     INITIAL_ADDRESS is less or equal to FINAL_ADDRESS,

   - if `downto' is specified, it is decreased by a corresponding value
     as long as INITIAL_ADDRESS is greater or equal to FINAL_ADDRESS.

   Since gpc provides a flat memory modell, all addresses are linear,
so they can be compared. Still, such loops should be used (if at all)
only for iterating through successive elements of an array.

   For sets:
   - STATEMENT is executed with the index variable (which must be
     ordinal and of the same type as the set elements) assuming every
     element in SOME_SET, however note that a set is a not-ordered
     structure.

   *Please note:* A modification of the index variable may result in
unpredictable action.

See also
--------

*Note Set Types::, *Note Pointer Arithmetics::, *Note repeat
Statement::, *Note for Statement::


File: gpc-hr.info,  Node: while Statement,  Next: repeat Statement,  Prev: for Statement,  Up: Statements

6.1.7.6 while Statement
.......................

The while loop has the following form
     while BOOLEAN_EXPRESSION do
       STATEMENT

   The `while' statement declares a loop which is executed while
BOOLEAN_EXPRESSION is true. Since the terminating condition is checked
before execution of the loop body, STATEMENT may never be executed.

See also
--------

*Note repeat Statement::, *Note for Statement::


File: gpc-hr.info,  Node: repeat Statement,  Next: asm Inline,  Prev: while Statement,  Up: Statements

6.1.7.7 repeat Statement
........................

     repeat
       STATEMENT;
       ...
       STATEMENT;
     until BOOLEAN_EXPRESSION

   The `repeat' ... `until' statement declares a loop which is repeated
until BOOLEAN_EXPRESSION is true. Since the terminating condition is
checked after execution of the loop body, the statement sequence is
executed at least once.

See also
--------

*Note while Statement::, *Note for Statement::


File: gpc-hr.info,  Node: asm Inline,  Next: with Statement,  Prev: repeat Statement,  Up: Statements

6.1.7.8 asm Inline
..................

@@ ????
     asm (StatementList: String);

   The `asm' inline statement is a GNU Pascal extension. It requires
its parameter to be AT&T-noted assembler statements, and therefore it
is not compatible with that one of Borland Pascal.  STATEMENTLIST is a
string containing asm statements separated by semicolons.


File: gpc-hr.info,  Node: with Statement,  Next: goto Statement,  Prev: asm Inline,  Up: Statements

6.1.7.9 with Statement
......................


File: gpc-hr.info,  Node: goto Statement,  Next: Procedure Call,  Prev: with Statement,  Up: Statements

6.1.7.10 goto Statement
.......................

@@ ????  This statement looks like this:
     goto LABEL

   (Under construction.)


File: gpc-hr.info,  Node: Procedure Call,  Next: The Declaring Statement,  Prev: goto Statement,  Up: Statements

6.1.7.11 Procedure Call
.......................

     SUBROUTINE_NAME;

   This statement calls the subroutine SUBROUTINE_NAME which can either
be a procedure or, if GNU extended syntax is turned on, a function. In
this case, the result is ignored.


File: gpc-hr.info,  Node: The Declaring Statement,  Next: Loop Control Statements,  Prev: Procedure Call,  Up: Statements

6.1.7.12 The Declaring Statement
................................

This statement allows to declare a variable within a statement part. It
looks like this:
     var
       VAR_IDENTIFIER: TYPE_IDENTIFIER;
   or
     var
       VAR_IDENTIFIER: TYPE_DEFINITION;
   and with initializing value:
     var
       VAR_IDENTIFIER: TYPE_IDENTIFIER value EXPRESSION;
   or
     var
       VAR_IDENTIFIER: TYPE_DEFINITION value EXPRESSION;

   Unlike in declaration parts, the initializing EXPRESSION does not
have to be a constant expression. Note that every declaring statement
has to start with `var'. The name space of the variable extends from
its declaration to the end of the current matching statement sequence
(which can be a statement part (of the program, a function, a procedure
or an operator) or, within that part, a begin end compound statement, a
repeat loop, or the else branch of a case statement). This statement is
a GNU Pascal extension.

See also
--------

*Note Type Definition::, *Note Data Types::


File: gpc-hr.info,  Node: Loop Control Statements,  Prev: The Declaring Statement,  Up: Statements

6.1.7.13 Loop Control Statements
................................

These are
     Continue;
   and
     Break;

   These simple statements _must not_ occur outside a loop, i.e. a
`for', `while' or `repeat' statement. `Continue' transfers control to
the beginning of the loop right by its call, `Break' exits the current
loop turn and continues loop execution.


File: gpc-hr.info,  Node: Modules and Units,  Prev: Statements,  Up: Source Structures

6.1.8 Import Part and Module/Unit Concept
-----------------------------------------

* Menu:

* Modules::  The source structure of ISO 10206 Extended Pascal Modules.
* Units::    The source structure of UCSD/Borland Pascal Units.


File: gpc-hr.info,  Node: Modules,  Next: Units,  Up: Modules and Units

6.1.8.1 The Source Structure of ISO 10206 Extended Pascal Modules
.................................................................

@@ Description missing here

   A module can have one or more `export' clauses and the name of an
`export' clause doesn't have to be equal to the name of the module.

   Sample module code with separate `interface' and `implementation'
parts:

     module DemoModule interface;  { interface part }

     export DemoModule = (FooType, SetFoo, GetFoo);

     type
       FooType = Integer;

     procedure SetFoo (f: FooType);
     function  GetFoo: FooType;

     end.

     module DemoModule implementation;  { implementation part }

     import
       StandardInput;
       StandardOutput;

     var
       Foo: FooType;

     { Note: the effect is the same as a `forward' directive would have:
       parameter lists and result types are not allowed in the
       declaration of exported routines, according to EP. In GPC, they
       are allowed, but not required. }
     procedure SetFoo;
     begin
       Foo := f
     end;

     function GetFoo;
     begin
       GetFoo := Foo
     end;

     to begin do
       begin
         Foo := 59;
         WriteLn ('Just an example of a module initializer. See comment below')
       end;

     to end do
       begin
         Foo := 0;
         WriteLn ('Goodbye')
       end;

     end.

   Alternatively the module interface and implementation may be
combined as follows:

     module DemoMod2;  { Alternative method }

     export Catch22 = (FooType, SetFoo, GetFoo);

     type
       FooType = Integer;

     procedure SetFoo (f: FooType);
     function  GetFoo: FooType;

     end; { note: this `end' is required here, even if the
            module-block below would be empty. }

     var
       Foo: FooType;

     procedure SetFoo;
     begin
       Foo := f
     end;

     function GetFoo;
     begin
       GetFoo := Foo
     end;

     end.

   Either one of the two methods may be used like this:

     program ModuleDemo (Output);

     import DemoModule;

     begin
       SetFoo (999);
       WriteLn (GetFoo);
     end.

     program ModDemo2 (Output);

     import Catch22 in 'demomod2.pas';

     begin
       SetFoo (999);
       WriteLn (GetFoo);
     end.

   Somewhat simpler GPC modules are also supported. *Please note:* This
is not supported in the Extended Pascal standard.

   This is a simpler module support that does not require exports,
imports, module headers etc.

   These non-standard simple GPC modules look like the following
example. They do not have an export part, do not have a separate
module-block, do not use import/export features.

   Instead, you have to emulate the exporting/importing yourself using
`attribute' and `external name'.

     module DemoMod3;

     type
       FooType = Integer;

     var
       Foo: FooType;

     procedure SetFoo (f: FooType); attribute (name = 'SetFoo');
     begin
       Foo := f
     end;

     function GetFoo: FooType; attribute (name = 'GetFoo');
     begin
       GetFoo := Foo;
     end;

     end.

     program ModDemo3 (Output);

     {$L demomod3.pas}  { explicitly link module }

     { Manually do the "import" from DemoMod3 }
     type
       FooType = Integer;

     procedure SetFoo (f: FooType); external name 'SetFoo';
     function  GetFoo: FooType;     external name 'GetFoo';

     begin
       SetFoo (999);
       WriteLn (GetFoo)
     end.

   Module initialization and finalization:

   The `to begin do' module initialization and `to end do' module
finalization constructs now work on _every_ target.

   By the way: The "GPC specific" module definition is almost identical
to the PXSC standard. With an additional keyword `global' which puts a
declaration into an export interface with the name of the module, it
will be the same. @@This is planned.


File: gpc-hr.info,  Node: Units,  Prev: Modules,  Up: Modules and Units

6.1.8.2 The Source Structure of UCSD/Borland Pascal Units
.........................................................

A generic GNU Pascal unit looks like the following:

     unit NAME;

     interface

     IMPORT_PART

     INTERFACE_PART

     implementation

     IMPLEMENTATION_PART

     INITIALIZATION_PART

     end.

   The NAME of the unit should coincide with the name of the file with
the extension stripped. (If not, you can tell GPC the file name with
`uses foo in 'bar.pas'', see *Note uses::.)

   The IMPORT_PART is either empty or contains a `uses' clause to
import other units. It may also consist of an ISO-style `import'
specification. Note that the implementation part is not preceeded by a
second import part in GPC (see *Note import::).

   The INTERFACE_PART consists of constant, type, and variable
declarations, procedure and function headings which may be freely mixed.

   The IMPLEMENTATION_PART is like the declaration part of a program,
but the headers of procedures and functions may be abbreviated:
Parameter lists and function results may be omitted for procedures and
functions already declared in the interface part.

   The INITIALIZATION_PART may be missing, or it may be a `begin'
followed by one or more statements, such that the unit has a statement
part between this `begin' and the final `end'. Alternatively, a unit
may have ISO-style module initializers and finalizers, see *Note to
begin do::, *Note to end do::.

   Note that GPC does _not_ yet check whether all interface
declarations are resolved in the same unit. The implementation of
procedures and functions which are in fact not used may be omitted,
and/or procedures and functions may be implemented somewhere else, even
in a different language. However, relying on a GPC bug (that will
eventually be fixed) is not a good idea, so this is not recommended.
Instead, declare such routines as `external'.

   A unit exports everything declared in the interface section. The
exported interface has the name of the unit and is compatible with
Extended Pascal module interfaces since GPC uses the same code to
handle both.


File: gpc-hr.info,  Node: Data Types,  Next: Operators,  Prev: Source Structures,  Up: Programming

6.2 Data Types
==============

* Menu:

* Type Definition::                The Declaration Part
* Ordinal Types::                  Built-in Ordinal Types
* Integer Types::                  Built-in Integer Types
* Real Types::                     Built-in Real Types
* String Types::                   Built-in Character and String Types
* Character Types::                Built-in Chararacter Types. See Ordinal Types
* Enumerated Types::               Enumerated Types. See also Ordinal Types
* File Types::                     Built-in Types for File Handling
* Boolean (Intrinsic)::            Built-in Type for Boolean values.
* Pointer (Intrinsic)::            The Intrinsic Pointer Type
* Type Definition Possibilities::  User-defined Types
* Machine-dependencies in Types::  Differences in Implementation


File: gpc-hr.info,  Node: Type Definition,  Next: Ordinal Types,  Up: Data Types

6.2.1 Type Definition
---------------------

As described in *Note Type Declaration::, a type declaration part looks
like this:
     type
        TYPE_IDENTIFIER = TYPE_DEFINITION;
        ...
        TYPE_IDENTIFIER = TYPE_DEFINITION;
   where the left side is the type declaration and the right one the
type definition side. GNU Pascal offers various possibilities to
implement highly specialized and problem-specific data types.


File: gpc-hr.info,  Node: Ordinal Types,  Next: Integer Types,  Prev: Type Definition,  Up: Data Types

6.2.2 Ordinal Types
-------------------

An ordinal type is one that can be mapped to a range of whole numbers.
It includes integer types, character types, enumerated types and
subrange types of them.

   A character type is represented by the intrinsic type `Char' which
can hold elements of the operating system's character set (usually
ASCII). Conversion between character types and integer types is
possible with the intrinsic functions `Ord' and `Chr'.

   An enumerated type defines a range of elements which are referred to
by identifiers. Conversion from enumerated types to integer types is
possible with the intrinsic function `Ord'. Conversion from integer to
ordinal types is only possible by type-casting or using the extended
form of `Succ'.

     var
       Foo: Char;       { foo can hold a character }
       Num: '0' .. '9'; { Can hold decimal digits, is a subrange type of Char }
       Day: (Monday, Tuesday, Wednesday, Thursday,
             Friday, Saturday, Sunday);  { Can hold weekdays }

See also
--------

*Note Ord::, *Note Chr::, *Note Type Casts::


File: gpc-hr.info,  Node: Integer Types,  Next: Real Types,  Prev: Ordinal Types,  Up: Data Types

6.2.3 Integer Types
-------------------

Besides `Integer', GNU Pascal supports a large zoo of integer types.
Some of them you will find in other compilers, too, but most are GNU
Pascal extensions, introduced for particular needs. Many of these types
are synonyms for each other. In total, GPC provides 20 built-in integer
types, plus seven families you can play with. (Four of these "families"
are signed and unsigned, packed and unpacked subrange types; the others
are explained below.)

* Menu:

* Natural Integer Types::
* Main Branch Integer Types::
* Integer Types with Specified Size::
* Integer Types and Compatibility::
* Summary of Integer Types::

   See also: *Note Subrange Types::.


File: gpc-hr.info,  Node: Natural Integer Types,  Next: Main Branch Integer Types,  Up: Integer Types

6.2.3.1 The CPU's Natural Integer Types
.......................................

For most purposes, you will always use `Integer', a signed integer type
which has the "natural" size of such types for the machine. On most
machines GPC runs on, this is a size of 32 bits, so `Integer' usually
has a range of `-2147483648..2147483647' (see *Note Integer::).

   If you need an unsigned integer type, the "natural" choice is
`Cardinal', also called `Word'. Like `Integer', it has 32 bits on most
machines and thus a range of `0..4294967295' (see *Note Cardinal::,
*Note Word::).

   These natural integer types should be your first choice for best
performance. For instance on an IA32 CPU operations with `Integer'
usually work faster than operations with shorter integer types like
`ShortInt' or `ByteInt' (see below).


File: gpc-hr.info,  Node: Main Branch Integer Types,  Next: Integer Types with Specified Size,  Prev: Natural Integer Types,  Up: Integer Types

6.2.3.2 The Main Branch of Integer Types
........................................

`Integer', `Cardinal', and `Word' define the three "main branches" of
GPC's integer types. You won't always be able to deal with the natural
size; sometimes something smaller or longer will be needed. Especially
when interfacing with libraries written in other languages such as C,
you will need equivalents for their integer types.

   The following variants of integer types (plus one Boolean type) are
guaranteed to be compatible to the respective types of GNU C as listed
below (whereas `Integer', `Cardinal' and `Word' themselves are _not_
guaranteed to be compatible to any given C type). The sizes given,
however, are _not_ guaranteed. They are just typical values currently
used on some platforms, but they may be actually shorter or longer on
any given platform.

signed         unsigned     also unsigned    GNU C equivalent            size in bits
                                                                         (example)
ByteInt        ByteCard     Byte             [un]signed char             8
ShortInt       ShortCard    ShortWord        [unsigned] short int        16
CInteger       CCardinal    CWord            [unsigned] int              32
MedInt         MedCard      MedWord          [unsigned] long int         32
LongInt        LongCard     LongWord         [unsigned] long long int    64
--             SizeType     --               size_t                      32
PtrDiffType    --           --               ptrdiff_t                   32
PtrInt         PtrCard      PtrWord          --                          32
--             CBoolean     --               _Bool, bool                 8

   Since we don't know whether `LongInt' will always remain the
"longest" integer type available - maybe GNU C will get `long long long
int', one day, which we will support as `LongLongInt' - we have added
the synonym `LongestInt' for the longest available singed integer type,
and the same holds for `LongestCard' and `LongestWord'.


File: gpc-hr.info,  Node: Integer Types with Specified Size,  Next: Integer Types and Compatibility,  Prev: Main Branch Integer Types,  Up: Integer Types

6.2.3.3 Integer Types with Specified Size
.........................................

In some situations you will need an integer type of a well-defined
size. For this purpose, GNU Pascal provides type attributes (*note
attribute::). The type

     Integer attribute (Size = 42)

is guaranteed to have a precision of 42 bits. In a realistic context,
you will most often give a power of two as the number of bits, and the
machine you will need it on will support variables of that size. If
this is the case, the specified precision will simultaneously be the
amount of storage needed for variables of this type.

   In short: If you want to be sure that you have a signed integer with
32 bits width, write `Integer attribute (Size = 32)', not just
`Integer' which might be bigger. The same works with unsigned integer
types such as `Cardinal' and `Word' and with Boolean types.

   This way, you _can't_ get a higher precision than that of
`LongestInt' or `LongestCard' (see *Note Main Branch Integer Types::).
If you need higher precision, you can look at the `GMP' unit (*note
GMP::) which provides integer types with arbitrary precision, but their
usage is different from normal integer types.


File: gpc-hr.info,  Node: Integer Types and Compatibility,  Next: Summary of Integer Types,  Prev: Integer Types with Specified Size,  Up: Integer Types

6.2.3.4 Integer Types and Compatibility
.......................................

If you care about ISO compliance, _only_ use `Integer' and subranges of
`Integer'.

   Some of GPC's non-ISO integer types exist in Borland Pascal, too:
`Byte', `ShortInt', `Word', and `LongInt'. The sizes of these types,
however, are not the same as in Borland Pascal. Even for `Byte' this is
not guaranteed (while probable, though).

   When designing GNU Pascal, we thought about compatibility to Borland
Pascal. Since GNU Pascal is (at least) a 32-bit compiler, `Integer'
_must_ have (at least) 32 bits. But what to do with `Word'? Same size
as `Integer' (like in BP) or 16 bits (like in BP)? We decided to make
`Word' the "natural-sized" unsigned integer type, thus making it (at
least) 32 bits wide. Similarly, we decided to give `LongInt' twice the
size of `Integer' (like in BP) rather than making it 32 bits wide (like
in BP). So `LongInt' has 64 bits, and `ShortInt' has 16 bits on the
IA32 platform.

   On the other hand, to increase compatibility to Borland Pascal and
Delphi, GPC provides the alias name `Comp' for `LongInt' (64 bits on
IA32) and `SmallInt' for `ShortInt' (16 bits on IA32). Note that BP
treats `Comp' as a "real" type and allows assignments like `MyCompVar
:= 42.0'. Since we don't consider this a feature, GPC does not copy
this behaviour.


File: gpc-hr.info,  Node: Summary of Integer Types,  Prev: Integer Types and Compatibility,  Up: Integer Types

6.2.3.5 Summary of Integer Types
................................

Here is a summary of all integer types defined in GPC. The sizes and
ranges are only _typical_ values, valid on some, but not all platforms.
Compatibility to GNU C however _is_ guaranteed.

*Note ByteInt::
     signed 8-bit integer type, `-128..128',
     compatible to `signed char' in GNU C.

*Note Byte: ByteCard.
     unsigned 8-bit integer type, `0..255',
     compatible to `unsigned char' in GNU C.

*Note ShortInt::
     signed 16-bit integer type, `-32768..32767',
     compatible to `short int' in GNU C.

*Note ShortWord: ShortCard.
     unsigned 16-bit integer type, `0..65535',
     compatible to `unsigned short int' in GNU C.

*Note Integer::
     signed 32-bit integer type, `-2147483648..2147483647',
     compatible to `int' in GNU C.

*Note Word: Cardinal.
     unsigned 32-bit integer type, `0..4294967295',
     compatible to `unsigned int' in GNU C.

*Note MedInt::
     signed 32-bit integer type, `-2147483648..2147483647',
     compatible to `long int' in GNU C.

*Note MedWord: MedCard.
     unsigned 32-bit integer type, `0..4294967295',
     compatible to `unsigned long int' in GNU C.

*Note LongInt::
     signed 64-bit integer type,
     `-9223372036854775808..9223372036854775807',
     compatible to `long long int' in GNU C.

*Note LongWord: LongCard.
     unsigned 64-bit integer type, `0..18446744073709551615',
     compatible to `unsigned long long int' in GNU C.

*Note LongestInt::
     signed 64-bit integer type,
     `-9223372036854775808..9223372036854775807'.

*Note LongestWord: LongestCard.
     unsigned 64-bit integer type, `0..18446744073709551615'.

*Note Comp::
     signed 64-bit integer type,
     `-9223372036854775808..9223372036854775807'.

*Note SmallInt::
     signed 16-bit integer type, `-32768..32767'.

*Note SizeType::
     integer type (usually unsigned) to represent the size of objects
     in memory

*Note PtrDiffType::
     signed integer type to represent the difference between two
     positions in memory

*Note PtrInt::
     signed integer type of the same size as a pointer

*Note PtrWord: PtrCard.
     unsigned integer type of the same size as a pointer

   To specify the number of bits definitely, use type attributes, *Note
attribute::.

     program IntegerTypesDemo (Output);

     var
       ByteVar: Byte;
       ShortIntVar: ShortInt;
       Foo: MedCard;
       Big: LongestInt;

     begin
       ShortIntVar := 1000;
       Big := MaxInt * ShortIntVar;
       ByteVar := 127;
       Foo := 16#deadbeef
     end.

   See also: *Note Subrange Types::.


File: gpc-hr.info,  Node: Real Types,  Next: String Types,  Prev: Integer Types,  Up: Data Types

6.2.4 Built-in Real (Floating Point) Types
------------------------------------------

GPC has three built-in floating point types to represent real numbers.
Each of them is available under two names (for compatibility to other
compilers and languages).

   For most purposes, you will always use `Real' which is the only one
of them that is part of Standard and Extended Pascal. If memory
constraints apply, you might want to choose `ShortReal' for larger
arrays. On the other hand, if high precision is needed, you can use
`LongReal'. When interfacing with libraries written in other languages
such as C, you will need the equivalents for their real types.

   Note that not all machines support longer floating point types, so
`LongReal' is the same as `Real' on these machines. Also, some machines
may support a longer type, but not do all arithmetic operations (e.g.
the `Sin' function, *Note Sin::) in a precision higher than that of
`Real'. If you need higher precision, you can look at the `GMP' unit
(*note GMP::) which provides rational and real numbers with arbitrary
precision, but their usage is different from normal real types.

   The following real types are guaranteed to be compatible to the real
types of GNU C. The sizes given, however, are _not_ guaranteed.  They
are just typical values used on any IEEE compatible floating point
hardware, but they may be different on some machines.

type name    alternative name    GNU C equivalent    size in bits (typically)
ShortReal    Single              float               32
Real         Double              double              64
LongReal     Extended            long double         80


File: gpc-hr.info,  Node: String Types,  Next: Character Types,  Prev: Real Types,  Up: Data Types

6.2.5 Strings Types
-------------------

There are several ways to use strings in GNU Pascal. One of them is the
use of the intrinsic string type `String' which is a predefined schema
type. The schema discriminant of this type holds the maximal length,
which is of type Integer, so values up to `MaxInt' can be specified.
For `String', an assignment is defined. There are many built-in
functions and procedures for comfortable strings handling.

   @@ ???? String procedures and functions.

   Another way to use strings is to use arrays of type `Char'. For
these, an intrinsic assignment is defined as well. Besides, `String'
and `Char' are assignment compatible. The preferred way, however, is
`String' because of the numerous possibilities for string handling.


File: gpc-hr.info,  Node: Character Types,  Next: Enumerated Types,  Prev: String Types,  Up: Data Types

6.2.6 Character Types
---------------------

Character types are a special case of ordinal types.

See also
--------

*Note Ordinal Types::, *Note Chr::, *Note Ord::, *Note Pred::, *Note
Succ::.


File: gpc-hr.info,  Node: Enumerated Types,  Next: File Types,  Prev: Character Types,  Up: Data Types

6.2.7 Enumerated Types
----------------------

     type
       ENUM_TYPE_IDENTIFIER = (IDENTIFIER, ..., IDENTIFIER);

   An enumerated type is a a special case of ordinal types and defines
a range of elements which are referred to by identifiers. Enumerated
types are ordered by occurence in the identifier list. So, they can be
used as index types in an array definition, and it is possible to
define subranges of them. Since they are ordered, they can be compared
to one another. The intrinsic function `Ord' applied to NAME_IDENTIFIER
returns the number of occurence in the identifier list (beginning with
zero), `Pred' and `Succ' return the predecessor and successor of
NAME_IDENTIFIER.  `Boolean' is a special case of an enumerated type.

See also
--------

*Note Ordinal Types::, *Note Array Types::, *Note Subrange Types::,
*Note Ord::, *Note Boolean::, *Note Char::, *Note Pred::, *Note Succ::.


File: gpc-hr.info,  Node: File Types,  Next: Boolean (Intrinsic),  Prev: Enumerated Types,  Up: Data Types

6.2.8 File Types
----------------

Files are used to store data permanently, normally on hard drives or
floppies. There are tree types of files available: text files, typed
and untyped files.

   Text files are used to store text in them, where typed files are
used to store many entries of the same type in them, e.g.  addresses.
Text files and typed files are accessible by `Read' and `Write'
operations and do not need the parameter `BlockSize' in `Reset' or
`Rewrite'.  On the other hand, untyped files are used to store any type
of information in them but you need to use `BlockWrite' or `BlockRead'
to store or retrieve data out of this file.

     var
       F1: Text;   { a textfile }
       F2: file of Real;   { a typed filed used to store real values in it }
       F3: File;   { an untyped file }

See also
--------

*Note File Routines::, *Note Write::, *Note Read::, *Note BlockRead::,
*Note BlockWrite::, *Note Reset::, *Note Rewrite::


File: gpc-hr.info,  Node: Boolean (Intrinsic),  Next: Pointer (Intrinsic),  Prev: File Types,  Up: Data Types

6.2.9 Boolean (Intrinsic)
-------------------------

The intrinsic Boolean represents boolean values, i.e. it can only assume
true and false (which are predefined constants). This type corresponds
to the enumerated type
     type
       Boolean = (False, True);
   Since it is declared this way, it follows:
     Ord (False) = 0
     Ord (True) = 1
     False < True
    There are four intrinsic logical operators. The logical `and',
`or' and `not'. In Borland Pascal and GNU Pascal, there is  a logical
"exclusive or" `xor'.

See also
--------

*Note Enumerated Types::, *Note and::, *Note or::, *Note not::, *Note
xor::


File: gpc-hr.info,  Node: Pointer (Intrinsic),  Next: Type Definition Possibilities,  Prev: Boolean (Intrinsic),  Up: Data Types

6.2.10 Pointer (Intrinsic)
--------------------------

The intrinsic Pointer Type is a so-called unspecified or typeless
pointer (i.e. a pointer which does not point to any type but holds
simply a memory address).

See also
--------

*Note Pointer Types::, *Note nil::


File: gpc-hr.info,  Node: Type Definition Possibilities,  Next: Machine-dependencies in Types,  Prev: Pointer (Intrinsic),  Up: Data Types

6.2.11 Type Definition Possibilities
------------------------------------

* Menu:

* Subrange Types::     Packed and non-packed Subranges
* Array Types::        Fields (Array Types)
* Record Types::       Structured Types (Record Types)
* Variant Records::    Record Types with Varying Fields
* Schema Types::       Schema Types
* Set Types::          Set Types
* Pointer Types::      Pointer Types
* Procedural Types::   Procedures Types
* Object Types::       Types for Object-Oriented Programming
* Type Initializers::  Types Carrying an Initial Value for Variables
* Restricted Types::   Hiding Internal Information about Types


File: gpc-hr.info,  Node: Subrange Types,  Next: Array Types,  Up: Type Definition Possibilities

6.2.11.1 Subrange Types
.......................

GNU Pascal supports Standard Pascal's subrange types:

     program SubrangeDemo;
     type
       MonthInt = 1 .. 12;
       Capital = 'A' .. 'Z';
       ControlChar = ^A .. ^Z;  { `^A' = `Chr (1)' is a BP extension }
     begin
     end.
   Also possible: Subranges of enumerated types:
     program EnumSubrangeDemo;
     type
       { This is an enumerated type. }
       Days = (Mon, Tue, Wed, Thu, Fri, Sat, Sun);

       { This is a subrange of `Days'. }
       Working = Mon .. Fri;

     begin
     end.

   To increase performance, variables of such a type are aligned in a
way which makes them fastest to access by the CPU. As a result, `1 ..
12' occupies 4 bytes of storage on an IA32 CPU.

   For the case you want to save storage at the expense of speed, GPC
provides a `packed' variant of these as an extension:

     program PackedSubrangeDemo;
     type
       MonthInt = packed 1 .. 12;
     begin
     end.

   A variable of this type occupies the shortest possible (i.e.,
addressable) space in memory - one byte on an IA32 compatible CPU.

   See also: *Note packed::.


File: gpc-hr.info,  Node: Array Types,  Next: Record Types,  Prev: Subrange Types,  Up: Type Definition Possibilities

6.2.11.2 Array Types
....................

     type
       ARRAY_TYPE_IDENTIFIER = array [INDEX_TYPE] of ELEMENT_TYPE
or
     type
       ARRAY_TYPE_IDENTIFIER = array [INDEX_TYPE, ..., INDEX_TYPE] of ELEMENT_TYPE

   The reserved word `array' defines an array type. INDEX_TYPE has to
be an ordinal type, subrange type or an enumerated type, where several
index types, separated by commas, are allowed. ELEMENT_TYPE is an
arbitrary type. An element of an array is accessed by
ARRAY_TYPE_VARIABLE [INDEX_NUMBER]. The upper and lower index bounds
can be determined by the intrinsic functions `High' and `Low'.

     type
       IntArray = array [1 .. 20] of Integer;
       Foo      = array [(Mo, Tu, We, Th, Fr, Sa, Su)] of Char;
       Bar      = array [0 .. 9, 'a' .. 'z', (Qux, Glork1, Fred)] of Real;
       Baz1     = array [1 .. 10] of IntArray;
       { equal (but declared differently): }
       Baz2     = array [1 .. 10, 1 .. 20] of Integer;

See also
--------

*Note High::, *Note Low::


File: gpc-hr.info,  Node: Record Types,  Next: Variant Records,  Prev: Array Types,  Up: Type Definition Possibilities

6.2.11.3 Record Types
.....................

     type
       RECORD_TYPE_IDENTIFIER = record
         FIELD_IDENTIFIER: TYPE_DEFINITION;
         ...
         FIELD_IDENTIFIER: TYPE_DEFINITION;
       end;

   or, with a variant part,

     type
       RECORD_TYPE_IDENTIFIER = record
         FIELD_IDENTIFIER: TYPE_DEFINITION;
         ...
         FIELD_IDENTIFIER: TYPE_DEFINITION;
       case bar: VARIANT_TYPE of
         SELECTOR: (FIELD_DECLARATIONS);
         SELECTOR: (FIELD_DECLARATIONS);
         ...
       end;

   or, without a variant selector field,

     type
       RECORD_TYPE_IDENTIFIER = record
         FIELD_IDENTIFIER: TYPE_DEFINITION;
         ...
         FIELD_IDENTIFIER: TYPE_DEFINITION;
       case VARIANT_TYPE of
         SELECTOR: (FIELD_DECLARATIONS);
         SELECTOR: (FIELD_DECLARATIONS);
         ...
       end;

   The reserved word `record' defines a structure of fields.  Records
can be `packed' to save memory usage at the expense of speed.

   The reserved word `record' and record types are defined in ISO 7185
Pascal. According to ISO Pascal, the variant type must be an
identifier. GNU Pascal, like UCSD and Borland Pascal, also allows a
subrange here.

   A record field is accessed by RECORD_TYPE_VARIABLE . FIELD_IDENTIFIER

   See also: *Note packed::, *Note case Statement::.


File: gpc-hr.info,  Node: Variant Records,  Next: Schema Types,  Prev: Record Types,  Up: Type Definition Possibilities

6.2.11.4 Variant Records
........................

GPC supports variant records like in EP and BP. The following
construction is not allowed in Extended Pascal, but in BP and GPC:

     program BPVariantRecordDemo;

     type
       PersonRec = record
         Age: Integer;
       case EyeColor: (Red, Green, Blue, Brown) of
         Red, Green : (WearsGlasses: Boolean);
         Blue, Brown: (LengthOfLashes: Integer);
       end;

     begin
     end.

   In EP, the variant field needs a type identifier, which, of course,
also works in GPC:

     program EPVariantRecordDemo;

     type
       EyeColorType = (Red, Green, Blue, Brown);

       PersonRec = record
         Age: Integer;
       case EyeColor: EyeColorType of
         Red, Green : (WearsGlasses: Boolean);
         Blue, Brown: (LengthOfLashes: Integer);
       end;

     begin
     end.


File: gpc-hr.info,  Node: Schema Types,  Next: Set Types,  Prev: Variant Records,  Up: Type Definition Possibilities

6.2.11.5 EP's Schema Types including `String'
.............................................

Schemata are types that depend on one or more variables, called
"discriminants". They are an ISO 10206 Extended Pascal feature.

     type
       RealArray (n: Integer) = array [1 .. n] of Real;
       Matrix (n, m: PositiveInteger) = array [1 .. n, 1 .. m] of Integer;

   The type `RealArray' in this example is called a Schema with the
discriminant `n'.

   To declare a variable of such a type, write:

     var
       Foo: RealArray (42);

   The discriminants of every global or local schema variable are
initialized at the beginning of the procedure, function or program
where the schema variable is declared.

   Schema-typed variables "know" about their discriminants.
Discriminants can be accessed just like record fields:

     program Schema1Demo;
     type
       PositiveInteger = 1 .. MaxInt;
       RealArray (n: Integer) = array [1 .. n] of Real;
       Matrix (n, m: PositiveInteger) = array [1 .. n, 1 .. m] of Integer;

     var
       Foo: RealArray (42);

     begin
       WriteLn (Foo.n)  { yields 42 }
     end.

   Schemata may be passed as parameters. While types of schema
variables must always have specified discriminants (which may be other
variables), formal parameters (by reference or by value) may be of a
schema type without specified discriminant. In this, the actual
parameter may posses any discriminant. The discriminants of the
parameters get their values from the actual parameters.

   Also, _pointers_ to schema variables may be declared without a
discriminant:

     program Schema2Demo;
     type
       RealArray (n: Integer) = array [1 .. n] of Real;
       RealArrayPtr = ^RealArray;
     var
       Bar: RealArrayPtr;
     begin
     end.

   When applying `New' to such a pointer, you must specify the intended
value of the discriminant as a parameter:

     New (Bar, 137)

   As a GNU Pascal extension, the above can also be written as

     Bar := New (RealArrayPtr, 137)

   The allocated variable behaves like any other schema variable:

     program Schema3Demo;
     type
       RealArray (n: Integer) = array [1 .. n] of Real;
       RealArrayPtr = ^RealArray;
     var
       Bar: RealArrayPtr;
       i: Integer;
     begin
       Bar := New (RealArrayPtr, 137);
       for i := 1 to Bar^.n do
         Bar^[i] := 42
     end.

   Since the schema variable "knows" its size, pointers to schemata can
be disposed just like other pointers:

     Dispose (Bar)

   Schemata are not limited to arrays. They can be of any type that
normally requires constant values in its definition, for instance
subrange types, or records containing arrays etc. (Sets do not yet
work.)

   References to the schema discriminants are allowed, and the `with'
statement is also allowed, so one can say:

     program SchemaWithDemo;
     type
       RealArray (n: Integer) = array [1 .. n] of Real;
     var
       MyArray: RealArray (42);
     begin
       WriteLn (MyArray.n);  { writes 42 }
       with MyArray do
         WriteLn (n);        { writes 42 }
     end.

   Finally, here is a somewhat exotic example. Here, a `ColoredInteger'
behaves just like an ordinary integer, but it has an additional
property `Color' which can be accessed like a record field.

     program SchemaExoticDemo;

     type
       ColorType = (Red, Green, Blue);
       ColoredInteger (Color: ColorType) = Integer;

     var
       Foo: ColoredInteger (Green);

     begin
       Foo := 7;
       if Foo.Color = Red then
         Inc (Foo, 2)
       else
         Foo := Foo div 3
     end.

   An important schema is the predefined `String' schema (according to
Extended Pascal). It has one predefined discriminant identifier
`Capacity'. GPC implements the `String' schema as follows:

     type
       String (Capacity: Cardinal) = record
         Length: 0 .. Capacity;
         Chars: packed array [1 .. Capacity + 1] of Char
       end;

   The `Capacity' field may be directly referenced by the user, the
`Length' field is referenced by a predefined string function `Length
(Str)' and contains the current string length.  `Chars' contains the
chars in the string. The `Chars' and `Length' fields cannot be directly
referenced by a user program.

   If a formal value parameter is of type `String' (with or without
discriminant), the actual parameter may be either a `String' schema, a
fixed string (character array), a single character, a string literal or
a string expression. If the actual parameter is a `String' schema, it
is copied for the parameter in the usual way. If it is not a schema, a
`String' schema is created automatically, the actual parameter is
copied to the new variable and the `Capacity' field of the new variable
is set to the length of the actual parameter.

   Actual parameters to `var' parameters of type `String' must be
`String' schemata, not string literals or character arrays.

     program StringDemo (Output);

     type
       SType = String (10);
       SPtr  = ^String;

     var
       Str : SType;
       Str2: String (100000);
       Str3: String (20) value 'string expression';
       DStr: ^String;
       ZStr: SPtr;
       Len : Integer value 256;
       Ch  : Char value 'R';

     { `String' accepts any length of strings }
     procedure Foo (z: String);
     begin
       WriteLn ('Capacity: ', z.Capacity);
       WriteLn ('Length  : ', Length (z));
       WriteLn ('Contents: ', z);
     end;

     { Another way to use dynamic strings }
     procedure Bar (SLen: Integer);
     var
       LString: String (SLen);
       FooStr: type of LString;
     begin
       LString := 'Hello world!';
       Foo (LString);
       FooStr := 'How are you?';
       Foo (FooStr);
     end;

     begin
       Str  := 'KUKKUU';
       Str2 := 'A longer string variable';
       New (DStr, 1000);  { Select the string Capacity with `New' }
       DStr^ := 'The maximum length of this is 1000 chars';
       New (ZStr, Len);
       ZStr^ := 'This should fit here';
       Foo (Str);
       Foo (Str2);
       Foo ('This is a constant string');
       Foo ('This is a ' + Str3);
       Foo (Ch);  { A char parameter to string routine }
       Foo ('');  { An empty string }
       Foo (DStr^);
       Foo (ZStr^);
       Bar (10000);
     end.

   In the above example, the predefined procedure `New' was used to
select the capacity of the strings. Procedure `Bar' also has a string
whose size depends of the parameter passed to it and another string
whose type will be the same as the type of the first string, using the
`type of' construct.

   All string and character types are compatible as long as the
destination string is long enough to hold the source in assignments.
If the source string is shorter than the destination, the destination
is automatically blank padded if the destination string is not of
string schema type.


File: gpc-hr.info,  Node: Set Types,  Next: Pointer Types,  Prev: Schema Types,  Up: Type Definition Possibilities

6.2.11.6 Set Types
..................

     SET_TYPE_IDENTIFIER = set of SET_ELEMENT_TYPE;

   SET_TYPE_IDENTIFIER is a set of elements from SET_ELEMENT_TYPE which
is either an ordinal type, an enumerated type or a subrange type.  Set
element representatives are joined together into a set by brackets:
     [SET_ELEMENT, ..., SET_ELEMENT]
   `[]' indicates the empty set, which is compatible with all set types.
Note: Borland Pascal restricts the maximal set size (i.e. the range of
the set element type) to 256, GNU Pascal has no such restriction.  The
number of elements a set variable is holding can be determined by the
intrinsic set function Card (which is a GNU Pascal extension, in
Extended Pascal and Borland Pascal you can use SizeOf instead but note
the element type size in bytes, then) to the set.  There are four
intrinsic binary set operations: the union `+', the intersection `*'
and the difference `-'. The symmetric difference `><' is an Extended
Pascal extension.

See also
--------

*Note Card::, *Note SizeOf::


File: gpc-hr.info,  Node: Pointer Types,  Next: Procedural Types,  Prev: Set Types,  Up: Type Definition Possibilities

6.2.11.7 Pointer Types
......................

     POINTER_TYPE_IDENTIFIER = ^TYPE_IDENTIFIER;

   A pointer of the type POINTER_TYPE_IDENTIFIER holds the address at
which data of the type TYPE_IDENTIFIER is situated.  Unlike other
identifier declarations, where all identifiers in definition part have
to be declared before, in a pointer type declaration TYPE_IDENTIFIER
may be declared after POINTER_TYPE_IDENTIFIER. The data pointed to is
accessed by `POINTER_TYPE_VARIABLE^'. To mark an unassigned pointer,
the `nil' constant (which stands for "not in list") has to be assigned
to it, which is compatible with all pointer types.

     type
       ItselfFoo = ^ItselfFoo;  { possible but mostly senseless }

       PInt      = ^Integer;    { Pointer to an Integer }

       PNode     = ^TNode;      { Linked list }
       TNode     = record
         Key     : Integer;
         NextNode: PNode;
       end;

     var
       Foo, Bar: PInt;

     begin
       Foo := Bar;  { Modify address which foo is holding }
       Foo^ := 5;   { Access data foo is pointing to }
     end.

   GPC also suports pointers to procedures or function and calls
through them. This is a non-standard feature.

     program ProcPtrDemo (Output);

     type
       ProcPtr = ^procedure (i: Integer);

     var
       PVar: ProcPtr;

     procedure WriteInt (i: Integer);
     begin
       WriteLn ('Integer: ', i : 1)
     end;

     begin
       { Let PVar point to function WriteInt }
       PVar := @WriteInt;

       { Call the function by dereferencing the function pointer }
       PVar^ (12345)
     end.

   See also: *Note Pointer (Intrinsic)::.


File: gpc-hr.info,  Node: Procedural Types,  Next: Object Types,  Prev: Pointer Types,  Up: Type Definition Possibilities

6.2.11.8 Procedural and Functional Types
........................................

For procedures without a parameter list:
     PROCEDURE_TYPE_IDENTIFIER = procedure NAME_IDENTIFIER;
   or functions:
     FUNCTION_TYPE_IDENTIFIER =
            function NAME_IDENTIFIER: FUNCTION_RESULT_TYPE;

   For procedures with a parameter list:
     PROCEDURE_TYPE_IDENTIFIER =
            procedure NAME_IDENTIFIER (PARAMETER_LIST);
   or functions:
     FUNCTION_TYPE_IDENTIFIER =
            function NAME_IDENTIFIER (PARAMETER_LIST): FUNCTION_RESULT_TYPE;

   Procedural types can be used as procedures or functions
respectively, but also a value can be assigned to them. Procedural
types are a Borland Pascal extension. In Borland Pascal,
FUNCTION_RESULT_TYPE can only be one of these types: ordinal types,
real types, pointer types, the intrinsic `String' type.  In GNU Pascal
every function result type for procedural types is allowed.

   BP has procedural and functional types:

     type
       CompareFunction = function (Key1, Key2: String): Integer;

     function Sort (Compare: CompareFunction);
     begin
       ...
     end;

   Standard Pascal has procedural and functional parameters:

     function Sort (function Compare (Key1, Key2: String): Integer);
     begin
       ...
     end;

   Both ways have pros and cons, e.g. in BP you can save, compare,
trade, etc. procedural values, or build arrays of them, while the SP
way does not require a type declaration and prevents problems with
uninitialized or invalid pointers (which in BP will usually crash the
program).

   GPC supports both ways. An important feature of Standard Pascal (but
not BP) that GPC also supports is the possibility to pass _local_
routines as procedural or functional parameters, even if the called
routine is declared far remote. The called routine can then call the
passed local routine and it will have access to the original caller's
local variables.

     program LocalProceduralParameterDemo;

     procedure CallProcedure (procedure Proc);
     begin
       Proc
     end;

     procedure MainProcedure;
     var LocalVariable: Integer;

       procedure LocalProcedure;
       begin
         WriteLn (LocalVariable)
       end;

     begin
       LocalVariable := 42;
       CallProcedure (LocalProcedure)
     end;

     begin
       MainProcedure
     end.

   See also: *Note The Procedure::, *Note The Function::, *Note
Subroutine Parameter List Declaration::, *Note Procedure Call::.


File: gpc-hr.info,  Node: Object Types,  Next: Type Initializers,  Prev: Procedural Types,  Up: Type Definition Possibilities

6.2.11.9 Object Types
.....................

Object types are used to encapsulate data and methods.  Furthermore,
they implement a mechanism for inheritance.

See also
--------

*Note OOP::


File: gpc-hr.info,  Node: Type Initializers,  Next: Restricted Types,  Prev: Object Types,  Up: Type Definition Possibilities

6.2.11.10 Initial values to type denoters
.........................................

A type may be initialized to a value of expression when it is declared,
like a variable, as in:

     program TypeVarInitDemo;
     type
       Int10   = Integer value 10;
       FooType = Real;
       MyType  = Char value Pred ('A');
       EType   = (a, b, c, d, e, f, g) value d;

     const
       Answer = 42;

     var
       ii : Int10;                    { Value of ii set to 10 }
       ch : MyType  value Pred ('z');
       aa : Integer value Answer + 10;
       foo: FooType value Sqr (Answer);
       e1 : EType;                    { value set to d }
       e2 : EType value g;            { value set to g }
     begin
     end.

   Extended Pascal requires the type initializers to be constant
expressions. GPC allows any valid expression.

   Note, however, that the expressions that affect the size of storage
allocated for objects (e.g. the length of arrays) may contain variables
only inside functions or procedures.

   GPC evaluates the initial values used for the type when an
identifier is declared for that type. If a variable is declared with a
type-denoter that uses a type-name which already has an initial value
the latter initialization has precedence.

   @@ GPC does not know how to calculate constant values for math
functions in the runtime library at compile time, e.g. `Exp (Sin
(2.4567))', so you should not use these kind of expressions in object
size expressions. (Extended Pascal allows this.)


File: gpc-hr.info,  Node: Restricted Types,  Prev: Type Initializers,  Up: Type Definition Possibilities

6.2.11.11 Restricted Types
..........................

GPC supports `restricted' types, defined in Extended Pascal. A value of
a restricted type may be passed as a value parameter to a formal
parameter possessing its underlying type, or returned as the result of
a function. A variable of a restricted type may be passed as a variable
parameter to a formal parameter possessing the same type or its
underlying type. No other operations, such as accessing a component of
a restricted type value or performing arithmetic, are possible.

     program RestrictedDemo;

     type
       UnrestrictedRecord = record
         a: Integer;
       end;
       RestrictedRecord = restricted UnrestrictedRecord;

     var
       r1: UnrestrictedRecord;
       r2: RestrictedRecord;
       i: restricted Integer;
       k: Integer;

     function AccessRestricted (p: UnrestrictedRecord): RestrictedRecord;
     var URes: UnrestrictedRecord;
     begin
       { The parameter is treated as unrestricted, even though the actual
         parameter may be restricted }
       URes.a := p.a;
       { It is allowed to assign a function result }
       AccessRestricted := URes;
     end;

     begin
       r1.a := 354;

       { Assigning a restricted function result to a restricted variable }
       { @@ Verify if this should really be allowed????? }
       r2 := AccessRestricted (r1);

       { Passing a restricted value to unrestricted formal parameter is ok }
       r2 := AccessRestricted (r2);

       {$ifdef BUG}
       { *** The following statements are not allowed *** }
       k := r2.a;      { field access (reading) }
       r2.a := 100;    { field access (writing) }
       r1 := r2;       { assignment source is restricted }
       r2 := r1;       { assignment target is restricted }
       r1 := AccessRestricted (r2); { assigning a restricted function
                                      result to an unrestricted object }
       i  := 16#ffff;  { assignment target is restricted }
       k  := i + 2;    { arithmetic with restricted value }
       {$endif}
     end.


File: gpc-hr.info,  Node: Machine-dependencies in Types,  Prev: Type Definition Possibilities,  Up: Data Types

6.2.12 Machine-dependencies in Types
------------------------------------

* Menu:

* Endianness::  How Integer Types are Stored on Different Machines
* Alignment::   How Variables are Placed in Memory


File: gpc-hr.info,  Node: Endianness,  Next: Alignment,  Up: Machine-dependencies in Types

6.2.12.1 Endianness
...................

Endianness means the order in which the bytes of a value larger than
one byte are stored in memory. This affects, e.g., integer values and
pointers while, e.g., arrays of single-byte characters are not
affected. The GPC `String' schema, however, contains `Capacity' and
`Length' fields before the character array.  These fields are integer
values larger than one byte, so the `String' schema _is_ affected by
endianness.

   Endianness depends on the hardware, especially the CPU. The most
common forms are:

   * "Little-endian"

     Little-endian machines store the least significant byte on the
     lowest memory address (the word is stored "little-end-first").

     E.g., if the 32 bit value `$deadbeef' is stored on memory address
     `$1234' on a little-endian machine, the following bytes will
     occupy the memory positions:

     Address       Value
     $1234         $ef
     $1235         $be
     $1236         $ad
     $1237         $de

     Examples for little-endian machines are IA32 and compatible
     microprocessors and Alpha processors.

   * "Big-endian"

     Big-endian machines store the most significant byte on the lowest
     memory address (the word is stored "big-end-first").

     E.g., if the 32 bit value `$deadbeef' is stored on memory address
     `$1234' on a big-endian machine, the following bytes will occupy
     the memory positions:

     Address       Value
     $1234         $de
     $1235         $ad
     $1236         $be
     $1237         $ef

     Examples for big-endian machines are the Sparc and Motorola m68k
     CPU families and most RISC processors. Big-endian byte order is
     also used in the Internet protocols.


   _Note:_ There are processors which can run in both little-endian and
big-endian mode, e.g. the MIPS processors. A single program, however,
(unless it uses special machine code instructions) will always run in
one endianness.

   Under normal circumstances, programs do not need to worry about
endianness, the CPU handles it by itself. Endianness becomes important
when exchanging data between different machines, e.g.  via binary files
or over a network. To avoid problems, one has to choose the endianness
to use for the data exchange. E.g., the Internet uses big-endian data,
and most known data formats have a specified endianness (usually that
of the CPU on which the format was originally created). If you define
your own binary data format, you're free to choose the endianness to
use.

   To deal with endianness, GPC predefines the symbol
`__BYTES_LITTLE_ENDIAN__' on little-endian machines and
`__BYTES_BIG_ENDIAN__' on big-endian machines. Besides, the Run Time
System defines the constant `BytesBigEndian' as False on little-endian
machines and True on big-endian machines.

   There are also the symbols `__BITS_LITTLE_ENDIAN__',
`__BITS_BIG_ENDIAN__', `__WORDS_LITTLE_ENDIAN__',
`__WORDS_BIG_ENDIAN__' and the constants `BitsBigEndian' and
`WordsBigEndian' which concern the order of bits within a byte (e.g.,
in packed records) or of words within multiword-numbers, but these are
usually less important.

   The Run Time System also contains a number of routines to convert
endianness and to read or write data from/to binary files in a given
endianness, independent of the CPU's endianness. These routines are
described in the RTS reference (*note Run Time System::), under
`endianness'. The demo program `endiandemo.pas' contains an example on
how to use these routines.


File: gpc-hr.info,  Node: Alignment,  Prev: Endianness,  Up: Machine-dependencies in Types

6.2.12.2 Alignment
..................

(Under construction.)  @@ ????


File: gpc-hr.info,  Node: Operators,  Next: Parameters,  Prev: Data Types,  Up: Programming

6.3 Operators
=============

GNU Pascal supports all operators of ISO Pascal and Borland Pascal.  In
addition, you can define your own operators according to the Pascal-SC
(PXSC) syntax.

* Menu:

* Built-in Operators::
* User-defined Operators::


File: gpc-hr.info,  Node: Built-in Operators,  Next: User-defined Operators,  Up: Operators

6.3.1 Built-in Operators
------------------------

The following table lists all built-in GNU Pascal operators, ordered by
precedence: `<' etc. have the lowest precedence, `not' etc. the
highest. As usual, the precedence of operators can be superseded with
parentheses.

   In an assignment statement, `:=' has lower precedence than all
operators. (This is rather obvious from the syntax of assignment
statements, and is merely noted for programmers familiar with C where
`=' is an operator.)

     <    =    >    in   <>   >=   <=
     +    -    or   +<   -<   +>   ->
     *    /    div  mod  and  shl  shr  xor  *<   /<   *>   />
     pow  **   ><
     not  @

   The Pascal-SC (PXSC) operators `+<', `-<', `+>', `->', `*<', `/<',
`*>', and `/>' are not yet implemented into GNU Pascal but may be
defined by the user (see below).


File: gpc-hr.info,  Node: User-defined Operators,  Prev: Built-in Operators,  Up: Operators

6.3.2 User-defined Operators
----------------------------

GNU Pascal allows the (re-)definition of binary operators according to
the Pascal-SC (PXSC) syntax. The following vector addition example
illustrates how to do this:

     program OperatorDemo;

     type
       Vector3 = record
         x, y, z: Real;
       end;

     var
       a, b, c: Vector3 = (1, 2, 3);

     operator + (u, v: Vector3) w: Vector3;
     begin
       w.x := u.x + v.x;
       w.y := u.y + v.y;
       w.z := u.z + v.z;
     end;

     begin
       c := a + b
     end.

   Between the closing parenthesis of the argument list and the result
variable (`w' in the above example), GPC allows an optional equal sign.
This is not allowed in PXSC, but it is consistent with Extended
Pascal's function result variable definitions, where the equal sign is
obligatory (but also optional in GPC).

   The argument types needn't be equal, and the name of the operator
may be an identifier instead of a known symbol. You cannot define _new_
symbols in GPC.

   The PXSC operators `+>', `+<', etc. for exact numerical calculations
currently are not implemented in GPC, but you can define them. Also,
the other real-type operators do _not_ meet the requirements of PXSC; a
module which fixes that would be a welcome contribution.


File: gpc-hr.info,  Node: Parameters,  Next: Pointer Arithmetics,  Prev: Operators,  Up: Programming

6.4 Procedure And Function Parameters
=====================================

* Menu:

* Protected Parameters::  Parameters declared `protected' or `const'
* Conformant Arrays::     The Standard way to pass arrays of variable size
* Open Arrays::           BP's alternative to Conformant Arrays


File: gpc-hr.info,  Node: Protected Parameters,  Next: Conformant Arrays,  Up: Parameters

6.4.1 Parameters declared as `protected' or `const'
---------------------------------------------------

All the following works in GPC:

     procedure Foo (protected a, b, c: Integer);    { 3 arguments }
     procedure Foo (a, b, c, protected: Integer);   { 4 arguments }
     procedure Foo (a, b, protected, c: Integer);   { 4 arguments }
     procedure Foo (protected: Integer);            { 1 argument  }
     procedure Foo (var protected: Integer);        { 1 argument  }
     procedure Foo (protected protected: Integer);  { 1 argument  }

   Furthermore, GPC supports `const', according to BP, which is
equivalent to either `protected' or `protected var', up to the
compiler's discretion.


File: gpc-hr.info,  Node: Conformant Arrays,  Next: Open Arrays,  Prev: Protected Parameters,  Up: Parameters

6.4.2 The Standard way to pass arrays of variable size
------------------------------------------------------

@@ (Under construction.)

   A feature of Standard Pascal level 1.


File: gpc-hr.info,  Node: Open Arrays,  Prev: Conformant Arrays,  Up: Parameters

6.4.3 BP's alternative to Conformant Arrays
-------------------------------------------

Borland Pascal "open array" formal parameters are implemented into GPC.
Within the function body, they have integer type index with lower bound
0.

   In constrast to conformant arrays (which are not supported by BP),
open arrays allow any ordinal type as the index of the actual parameter
(which is useful, e.g., if you want to be able to pass values of any
enumeration type). However, they lose information about the lower bound
(which is a problem, e.g., if you want to return information to the
caller that relates to the actual array index, like the function
`IOSelect' in the Run Time System does).


File: gpc-hr.info,  Node: String Slice Access,  Next: Type Casts,  Prev: Pointer Arithmetics,  Up: Programming

6.5 Accessing parts of strings (and other arrays)
=================================================

GPC allows the access of parts ("slices") of strings as defined in
Extended Pascal. For example:

     program StringSliceDemo;

     const
       HelloWorld = 'Hello, world!';

     begin
       WriteLn (HelloWorld[8 .. 12])  { yields `world' }
     end.

   As an extension, it also allows write access to a string slice:

     program SliceWriteDemo;

     var
       s: String (42) = 'Hello, world!';

     begin
       s[8 .. 12] := 'folks';
       WriteLn (s)  { yields `Hello, folks!' }
     end.

   As a further extension, GPC allows slice access also to non-string
arrays. However, the usefulness of this feature is rather limited
because of Pascal's strict type checking rules: If you have, e.g., an
`array [1 .. 10] of Integer' and take a slice `[1 .. 5]' of it, it will
not be compatible to another `array [1 .. 5] of Integer' because
distinct array types are not compatible in Pascal, even if they look
the same.

   However, array slice access can be used in connection with
conformant or open array parameters. See the program
`arrayslicedemo.pas' (in the `demos' directory) for an example.


File: gpc-hr.info,  Node: Pointer Arithmetics,  Next: String Slice Access,  Prev: Parameters,  Up: Programming

6.6 Pointer Arithmetics
=======================

GPC allows to increment, decrement, compare, and subtract pointers or
to use them in `for' loops just like the C language.

   GPC implements the address operator `@' (a Borland Pascal extension).

     program PointerArithmeticDemo;
     var
       a: array [1 .. 7] of Char;
       p, q: ^Char;
       i: Integer;

     {$X+}  { We need extended syntax for pointer arithmetic }

     begin
       for p := @a[1] to @a[7] do
         p^ := 'x';

       p := @a[7];
       q := @a[3];
       while p > q do
         begin
           p^ := 'y';
           Dec (p)
         end;

       p := @a[7];
       q := @a[3];
       i := q - p;    { yields 4 }
     end.

   Incrementing a pointer by one means to increment the address it
contains by the size of the variable it is pointing to. For typeless
pointers (`Pointer'), the address is incremented by one instead.

   Similar things hold when decrementing a pointer.

   Subtracting two pointers yields the number of variables pointed to
between both pointers, i.e. the difference of the addresses divided by
the size of the variables pointed to. The pointers must be of the same
type.


File: gpc-hr.info,  Node: Type Casts,  Next: OOP,  Prev: String Slice Access,  Up: Programming

6.7 Type Casts
==============

In some cases, especially in low-level situations, Pascal's strong
typing can be an obstacle. To temporarily circumvent this, GPC defines
explicit "type casts" in a Borland Pascal compatible way.

   There are two kinds of type casts, value type casts and variable type
casts.

   Value type casts

   To convert a value of one data type into another type, you can use
the target type like the name of a function that is called. The value
to be converted can be a variable or an expression. Both the value's
type and the destination type must be ordinal or pointer types. The
ordinal value (extended to pointers to mean the address) is preserved
in the cast.

   An example:

     program TypeCastDemo;

     var
       Ch: Char;
       i: Integer;

     begin
       i := Integer (Ch)
     end.

   Another, more complicated, example:

     program TypeCst2Demo;

     type
       CharPtr = ^Char;
       CharArray = array [0 .. 99] of Char;
       CharArrayPtr = ^CharArray;

     var
       Foo1, Foo2: CharPtr;
       Bar: CharArrayPtr;

     {$X+} { We need extended syntax in order to use ``Succ'' on a pointer }

     begin
       Foo1 := CharPtr (Bar);
       Foo2 := CharPtr (Succ (Bar))
     end.

   However, because of risks involved with type casts, explained below,
and because type-casts are non-standard, you should try to avoid type
casts whenever possible - and it should be possible in most cases. For
instance, the first example above could use the built-in function "Ord"
instead of the type cast:

     i := Ord (Ch);

   The assignments in the second example could be written in the
following way without any type casts:

     Foo1 := @Bar^[0];
     Foo2 := @Bar^[1];

   Note: In the case of pointers, a warning is issued if the
dereferenced target type requires a bigger alignment than the
dereferenced source type (see *Note Alignment::).

   Variable type casts

   It is also possible to temporarily change the type of a variable
(more generally, any "lvalue", i.e. something whose address can be
taken), without converting its contents in any way. This is called
variable type casting.

   The syntax is the same as for value type casting. The type-casted
variable is still the same variable (memory location) as the original
one, just with a different type. Outside of the type cast, the variable
keeps its original type.

   There are some important differences between value and variable type
casting:

   * Variable type casting only works on lvalues, not on expressions.

   * The result of a variable type casting is still an lvalue, so it can
     be used, e.g., on the left side of an assignment, or as the operand
     of an address operator, or passed by reference to a procedure.

   * No values are converted in variable type-casting. The contents of
     the variable, seen as a raw bit pattern, are just interpreted
     according to the new type.

   * Because bit patterns are just interpreted differently, the source
     and target type must have the same size. If this is not the case,
     GPC will give a warning.

   * Beware: Variable type casts might have unexpected effects on
     different platforms since you cannot rely on a specific way the
     data is stored (e.g. see *Note Endianness::).


   There are cases where a type-cast could be either a value or a
variable cast. This is when both types are ordinal or pointer, and of
the same size, and the value is an lvalue. Fortunately, in those cases,
the results of both forms are the same, since the same ordinal values
(or pointer addresses) are represented by the same bit patterns (when
of the same size). Therefore, it doesn't matter which form of
type-casting is actually used in these cases.

   When dealing with objects (see *Note OOP::), it is sometimes
necessary to cast a polymorphic pointer to an object into a pointer to
a more specialized (derived) object (after checking the actual type).
However, the `as' operator is a safer approach, so type-casts should be
used there only for backward-compatibility (e.g., to BP).

   See also: *Note absolute::, *Note Alignment::, *Note Endianness::,
*Note OOP::, *Note Ord::, *Note Chr::, *Note Round::, *Note Trunc::.


File: gpc-hr.info,  Node: OOP,  Next: Compiler Directives,  Prev: Type Casts,  Up: Programming

6.8 Object-Oriented Programming
===============================

GNU Pascal follows the object model of Borland Pascal 7.0. The BP
object extensions are almost fully implemented into GPC. This includes
inheritance, virtual and non-virtual methods, constructors,
destructors, pointer compatibility, extended `New' syntax (with
constructor call and/or as a Boolean function), extended `Dispose'
syntax (with destructor call).

   The Borland object model is different from the ISO draft, but it
will not be too difficult now to implement that too (plus the Borland
Delphi Object Extensions which are quite similar to the ISO draft).

   The syntax for an object type declaration is as follows:

     program ObjectDemo;

     type
       Str100 = String (100);

       FooParentPtr = ^FooParent;
       FooPtr = ^Foo;

       FooParent = object
         constructor Init;
         destructor Done; virtual;
         procedure Bar (c: Real); virtual;
         function Baz (b, a, z: Char) = s: Str100;  { not virtual }
       end;

       Foo = object (FooParent)
         x, y: Integer;
         constructor Init (a, b: Integer);
         destructor Done; virtual;
         procedure Bar (c: Real); virtual;  { overrides `FooParent.Bar' }
         z: Real;  { GPC extension: data fields after methods }
         function Baz: Boolean;  { new function }
       end;

     constructor FooParent.Init;
     begin
       WriteLn ('FooParent.Init')
     end;

     destructor FooParent.Done;
     begin
       WriteLn ('I''m also done.')
     end;

     procedure FooParent.Bar (c: Real);
     begin
       WriteLn ('FooParent.Bar (', c, ')')
     end;

     function FooParent.Baz (b, a, z: Char) = s: Str100;
     begin
       WriteStr (s, 'FooParent.Baz (', b, ', ', a, ', ', z, ')')
     end;

     constructor Foo.Init (a, b: Integer);
     begin
       inherited Init;
       x := a;
       y := b;
       z := 3.4;
       FooParent.Bar (1.7)
     end;

     destructor Foo.Done;
     begin
       WriteLn ('I''m done.');
       inherited Done
     end;

     procedure Foo.Bar (c: Real);
     begin
       WriteLn ('Foo.Bar (', c, ')')
     end;

     function Foo.Baz: Boolean;
     begin
       Baz := True
     end;

     var
       Ptr: FooParentPtr;

     begin
       Ptr := New (FooPtr, Init (2, 3));
       Ptr^.Bar (3);
       Dispose (Ptr, Done);
       New (Ptr, Init);
       with Ptr^ do
         WriteLn (Baz ('b', 'a', 'z'))
     end.

   Remarks:

   * The ordering of data fields and methods can be mixed.

   * GPC supports the `public' and `private' declarations like BP, and
     in addition also `protected' (scope limited to the current type
     and its descendants).

   * Constructors and destructors are ordinary functions, internally.
     When a constructor is called, GPC creates some inline code to
     initialize the object; destructors do nothing special.

   A pointer to `FooParent' may be assigned the address of a `Foo'
object. A `FooParent' formal `var' parameter may get a `Foo' object as
the actual parameter. In such cases, a call to a `virtual' method calls
the child's method, whereas a call to a non-`virtual' method selects
the parent's one:

     var
       MyFooParent: FooParentPtr;
       SomeFoo: Foo;

     [...]

       SomeFoo.Init (4, 2);
       MyFooParent := @SomeFoo;
       MyFooParent^.bar (3.14);  { calls `foo.bar' }
       MyFooParent^.baz ('b', 'a', 'z');  { calls `fooParent.baz' }
       if SomeFoo.baz then  { calls `foo.baz' }
         WriteLn ('Baz!');

   In a method, an overwritten method of a parent object can be called
either prefixing it with the parent type name, or using the keyword
`inherited':

     procedure Foo.Bar (c: Real);
     begin
       z := c;
       inherited bar (z)  { or: FooParent.Bar (z) }
     end;

   Use `FooParent.bar (z)' if you want to be sure that _this_ method is
called, even if somebody decides not to derive `foo' directly from
`fooParent' but to have some intermediate object.  If you want to call
the method `bar' of the immediate parent - whether it be `fooParent' or
whatever - use `inherited bar (z)'.

   To allocate an object on the heap, use `New' in one of the following
manners:

     var
       MyFoo: FooPtr;

       [...]

       New (MyFoo, Init (4, 2));

       MyFooParent := New (FooPtr, Init (4, 2))

   The second possibility has the advantage that `MyFoo' needn't be a
`FooPtr' but can also be a `FooParentPtr', i.e. a pointer to an
ancestor of `foo'.

   Destructors can and should be called within Dispose:

     Dispose (MyFooParent, Fini)


File: gpc-hr.info,  Node: Compiler Directives,  Next: Library Routines,  Prev: OOP,  Up: Programming

6.9 Compiler Directives And The Preprocessor
============================================

GPC, like UCSD Pascal and BP, treats comments beginning with a `$'
immediately following the opening `{' or `(*' as a compiler directive.
As in Borland Pascal, `{$...}' and `(*$...*)' are equivalent. When a
single character plus a `+' or `-' follows, this is also called a
compiler switch.  All of these directives are case-insensitive (but
some of them have case-sensitive arguments). Directives are local and
can be changed during one compilation (except include files etc. where
this makes no sense).

   In general, compiler directives are compiler-dependent. (E.g., only
the include directive `{$I FileName}' is common to UCSD and BP.)
Because of BP's popularity, GPC supports all of BP's compiler
directives (and ignores those that are unnecessary on its platforms -
these are those not listed below), but it knows a lot more directives.

   Some BP directives are - of course not by chance - just an
alternative notation for C preprocessor directives. But there are
differences: BP's "conditional" definitions (`{$define Foo}') go into
another name space than the program's definitions. Therefore you can
define conditionals and check them via `{$ifdef Foo}', but the program
will not see them as an identifier `Foo', so macros do not exist in
Borland Pascal.

   GPC does support macros, but disables this feature when the
`--no-macros' option or the dialect option `--borland-pascal' or
`--delphi' is given, to mimic BP's behaviour. Therefore, the following
program will react differently when compiled with GPC either without
special options or with, e.g., the `--borland-pascal' option (and in
the latter case, it behaves the same as when compiled with BP).

     program MacroDemo;

     const Foo = 'Borland Pascal';

     {$define Foo 'Default'}

     begin
       WriteLn (Foo)
     end.

   Of course, you should not rely on such constructs in your programs.
To test if the program is compiled with GPC, you can test the `__GPC__'
conditional, and to test the dialect used in GPC, you can test the
dialect, e.g., with `{$ifopt borland-pascal}'.

   In general, almost every GPC specific command line option (*note GPC
Command Line Options::) can be turned into a compiler directive
(exceptions are those options that contain directory names, such as
`--unit-path', because they refer to the installation on a particular
system, and therefore should be set system-wide, rather than in a
source file):

     --foo       {$foo}
     --no-foo    {$no-foo}
     -Wbar       {$W bar}     { note the space after the `W' }
     -Wno-bar    {$W no-bar}

   The following table lists some such examples as well as all those
directives that do not correspond to command-line options or have
syntactical alternatives (for convenience and/or BP compatibility).

     --[no-]short-circuit   $B+ $B- like in Borland Pascal:
                                    $B- means short-circuit Boolean
                                    operators; $B+ complete evaluation

     --[no-]io-checking     $I+ $I- like in Borland Pascal:
                                    enable/disable I/O checking

     --[no-]range-checking  $R+ $R- like in Borland Pascal:
                                    enable/disable range checking

     --[no-]stack-checking  $S+ $S- like in Borland Pascal:
                                    enable/disable stack checking

     --[no-]typed-address   $T+ $T- like in Borland Pascal:
                                    make the result of the address
                                    operator and the Addr function a
                                    typed or untyped pointer

     -W[no-]warnings        $W+ $W- enable/disable warnings. Note: in
                                    `--borland-pascal' mode, the
                                    short version is disabled because
                                    $W+/$W- has a different meaning in
                                    Borland Pascal (which can safely be
                                    ignored in GPC), but the long version
                                    is still available.

     --[no-]extended-syntax $X+ $X- mostly like in Borland Pascal:
                                    enable/disable extended syntax
                                    (ignore function resuls, operator
                                    definitions, `PChar', pointer
                                    arithmetic, ...)

     --borland-pascal               disable or warn about GPC features
     --extended-pascal              not supported by the standard or
     --pascal-sc                    dialect given, do not warn about its
     etc.                           ``dangerous'' features (especially BP).
                                    The dialect can be changed during one
                                    compilation via directives like,
                                    e.g., `{$borland-pascal}'.

     {$M Hello!}                    write message `Hello!' to
                                    standard error during compilation. In
                                    `--borland-pascal' mode, it is
                                    ignored it if only numbers follow
                                    (for compatibility to Borland
                                    Pascal's memory directive)

     {$define FOO}                  like in Borland Pascal:
     or                             define FOO (for conditional compilation)
     {$CIDefine FOO}                (case-insensitively)

     --cidefine=FOO                 the same on the command line

     {$CSDefine FOO}                define FOO case-sensitively

     -D FOO                         the same on the command line
     or                             Note: `--define' on the command
     --csdefine=FOO                 line is case-sensitive like in GCC,
     or                             but `{$define}' in the source code
     --define=FOO                   is case-insensitive like in BP

     {$define loop while True do}   define `loop' to be `while True do'
     or                             as a macro like in C. The name of the
     {$CIDefine loop ...}           macro is case-insensitive. Note:
                                    Macros are disabled in
                                    `--borland-pascal' mode because BP
                                    doesn't support macros.

     --cidefine="loop=..."          the same on the command line

     {$CSDefine loop ...}           define a case-sensitive macro

     --csdefine="loop=..."          the same on the command line
     or
     --define="loop=..."

     {$I FileName}                  like in Borland Pascal:
                                    include `filename.pas'
                                    (the name is converted to lower case)

     {$undef FOO}                   like in Borland Pascal: undefine FOO

     {$ifdef FOO}                   conditional compilation
       ...                          (like in Borland Pascal).
     {$else}                        Note: GPC predefines the symbol
       ...                          `__GPC__' (with two leading
     {$endif}                       and trailing underscores).

     {$include "filename.pas"}      include (case-sensitive)

     {$include <filename.pas>}      the same, but don't search in the
                                    current directory
   ...and all the other C preprocessor directives.

   You also can use the preprocessor directives in C style, e.g.
`#include', but this is deprecated because of possible confusion with
Borland Pascal style `#42' character constants.  Besides, in the Pascal
style, e.g. `{$include "foo.bar"}', there may be more than one
directive in the same line.


File: gpc-hr.info,  Node: Library Routines,  Next: Other Languages,  Prev: Compiler Directives,  Up: Programming

6.10 Routines Built-in or in the Run Time System
================================================

In this section we describe the routines and other declarations that
are built into the compiler or part of the Run Time System, sorted by
topics.

* Menu:

* File Routines::
* String Operations::
* Accessing Command Line Arguments::
* Memory Management Routines::
* Operations for Integer and Ordinal Types::
* Complex Number Operations::
* Set Operations::
* Date And Time Routines::


File: gpc-hr.info,  Node: File Routines,  Next: String Operations,  Up: Library Routines

6.10.1 File Routines
--------------------

Extended Pascal treats files quite differently from Borland Pascal.
GPC supports both forms, even in mixed ways, and provides many
extensions.

   @@ A lot missing here

   * An example of getting the size of a file (though a `FileSize'
     function is already built-in).

          function FileSize (FileName : String) : LongInt;
          var
            f: bindable file [0 .. MaxInt] of Char;
            b: BindingType;
          begin
            Unbind (f);
            b := Binding (f);
            b.Name := FileName;
            Bind(f, b);
            b := Binding(f);
            SeekRead (f, 0);
            if Empty (f) then
              FileSize := 0
            else
              FileSize := LastPosition (f) + 1;
            Unbind(f);
          end;

     Prospero's Extended Pascal has a bug in this case. Replace the
     MaxInt in the type definition of f by a sufficiently large
     integer. GNU Pascal works correct in this case.

   * GPC implements "lazy" text file I/O, i.e. does a `Put' as soon as
     possible and a `Get' as late as possible. This should avoid most
     of the problems sometimes considered to be the most stupid feature
     of Pascal. When passing a file buffer as parameter the buffer is
     validated when the parameter is passed.

   * GPC supports direct access files. E.g., declaring a type for a
     file that contains 100 integers.

          program DirectAccessFileDemo;
          type
            DFile = file [1 .. 100] of Integer;
          var
            F: DFile;
            P, N: 1 .. 100;
          begin
            Rewrite (F);
            P := 42;
            N := 17;
            SeekWrite (F, P);
            Write (F, N)
          end.

     The following direct access routines may be applied to a direct
     access file:

    `SeekRead   (F, N);      { Open file in inspection mode, seek to record N }'

    `SeekWrite  (F, N);      { Open file in generation mode, seek to record N }'

    `SeekUpdate (F, N);      { Open file in update mode, seek to record N }'

    `Update (F);             { Writes F^, position not changed. F^ kept. }'

    `p := Position (F);      { Yield the current record number }'

    `p := LastPosition (F);  { Yield the last record number in file }'

     If the file is open for inspection or update, `Get' may be applied.
     If the file is open for generation or update, `Put' may be applied.

   * In BP, you can associate file variables with files using the
     `Assign' procedure which GPC supports.

          program AssignTextDemo;
          var
            t: Text;
            Line: String (4096);
          begin
            Assign (t, 'mytext.txt');
            Reset (t);
            while not EOF (t) do
              begin
                ReadLn (t, Line);
                WriteLn (Line)
              end
          end.

   * In Extended Pascal, files are considered entities external to your
     program. External entities, which don't need to be files, need to
     be bound to a variable your program. Any variable to which external
     entities can be bound needs to be declared `bindable'. Extended
     Pascal has the `Bind' function that binds a variable to an
     external entity as well as `Unbind' to undo a binding and the
     function `Binding' to get the current binding of a variable.

     GPC supports these routines when applied to files. The compiler
     will reject binding of other object types.

     Only the fields `Bound' and `Name' of the predefined record type
     `BindingType' are required by Extended Pascal.  Additionally, GPC
     implements some extensions. For the full definition of
     `BindingType', see *Note BindingType::.

     The following is an example of binding:

          program BindingDemo (Input, Output, f);

          var
            f: bindable Text;
            b: BindingType;

          procedure BindFile (var f: Text);
          var
            b: BindingType;
          begin
            Unbind (f);
            b := Binding (f);
            repeat
              Write ('Enter a file name: ');
              ReadLn (b.Name);
              Bind (f, b);
              b := Binding (f);
              if not b.Bound then
                WriteLn ('File not bound -- try again.')
            until b.Bound
          end;

          begin
            BindFile (f);
            { Now the file f is bound to an external file. We can use the
              implementation defined fields of BindingType to check if the
              file exists and is readable, writable or executable. }
            b := Binding (f);
            Write ('The file ');
            if b.Existing then
              WriteLn ('exists.')
            else
              WriteLn ('does not exist.');
            Write ('It is ');
            if not b.Readable then Write ('not ');
            Write ('readable, ');
            if not b.Writable then Write ('not ');
            Write ('writable and ');
            if not b.Executable then Write ('not ');
            WriteLn ('executable.')
          end.


   Note that Prospero's Pascal defaults to creating the file if it does
not exists! You need to use Prospero's local addition of setting
`b.Existing' to `True' to work-around this. GPC does not behave like
this.


File: gpc-hr.info,  Node: String Operations,  Next: Accessing Command Line Arguments,  Prev: File Routines,  Up: Library Routines

6.10.2 String Operations
------------------------

In the following description, `s1' and `s2' may be arbitrary string
expressions, `s' is a variable of string type.

`WriteStr (s, write-parameter-list)'

`ReadStr (s1, read-parameter-list)'
     Write to a string and read from a string.  The parameter lists are
     identical to `Write'/`Read' from `Text' files. The semantics is
     closely modeled after file I/O.

`Index (s1, s2)'
     If `s2' is empty, return 1 else if `s1' is empty return 0 else
     returns the position of `s2' in `s1' (an integer).

`Length (s1)'
     Return the length of `s1' (an integer from `0 .. s1.Capacity').

`Trim (s1)'
     Returns a new string with spaces stripped of the end of `s'.

`SubStr (s1, i)'

`SubStr (s1, i, j)'
     Return a new substring of `s1' that contains `j' characters
     starting from `i'. If `j' is missing, return all the characters
     starting from `i'.

`EQ (s1, s2)'

`NE (s1, s2)'

`LT (s1, s2)'

`LE (s1, s2)'

`GT (s1, s2)'

`GE (s1, s2)'
     Lexicographic comparisons of `s1' and `s2'. Returns a boolean
     result. Strings are not padded with spaces.

`s1 =  s2'

`s1 <> s2'

`s1 <  s2'

`s1 <= s2'

`s1 >  s2'

`s1 >= s2'
     Lexicographic comparisons of `s1' and `s2'. Returns a boolean
     result. The shorter string is blank padded to length of the longer
     one, but only in `--extended-pascal' mode.

   GPC supports string catenation with the `+' operator or the `Concat'
function. All string-types are compatible, so you may catenate any
chars, fixed length strings and variable length strings.

     program ConcatDemo (Input, Output);

     var
       Ch  : Char;
       Str : String (100);
       Str2: String (50);
       FStr: packed array [1 .. 20] of Char;

     begin
        Ch := '$';
        FStr := 'demo';  { padded with blanks }
        Write ('Give me some chars to play with: ');
        ReadLn (Str);
        Str := '^' + 'prefix:' + Str + ':suffix:' + FStr + Ch;
        WriteLn (Concat ('Le', 'ng', 'th'), ' = ', Length (Str));
        WriteLn (Str)
     end.

   Note: The length of strings in GPC is limited only by the range of
`Integer' (at least 32 bits, i.e., 2 GB, on most platforms), or the
available memory, whichever is smaller).

   When trying to write programs portable to other EP compilers, it is
however safe to assume a limit of about 32 KB. At least Prospero's
Extended Pascal compiler limits strings to 32760 bytes. DEC Pascal
limits strings to 65535 bytes.


File: gpc-hr.info,  Node: Accessing Command Line Arguments,  Next: Memory Management Routines,  Prev: String Operations,  Up: Library Routines

6.10.3 Accessing Command Line Arguments
---------------------------------------

GPC supports access to the command line arguments with the BP
compatible `ParamStr' and `ParamCount' functions.

   * `ParamStr[0]' is the program name,

   * `ParamStr[1] .. ParamStr[ParamCount]' are the arguments.

   The program below accesses the command line arguments.

     program CommandLineArgumentsDemo (Output);

     var
       Counter: Integer;

     begin
       WriteLn ('This program displays command line arguments one per line.');
       for Counter := 0 to ParamCount do
         WriteLn ('Command line argument #', Counter, ' is `',
                  ParamStr (Counter), '''')
     end.


File: gpc-hr.info,  Node: Memory Management Routines,  Next: Operations for Integer and Ordinal Types,  Prev: Accessing Command Line Arguments,  Up: Library Routines

6.10.4 Memory Management Routines
---------------------------------

Besides the standard `New' and `Dispose' routines, GPC also allows BP
style dynamic memory management with `GetMem' and `FreeMem':

     GetMem (MyPtr, 1024);
     FreeMem (MyPtr, 1024);

   One somehow strange feature of Borland is *not* supported: You
cannot free parts of a variable with `FreeMem', while the rest is still
used and can be freed later by another `FreeMem' call:

     program PartialFreeMemDemo;

     type
       Vector = array [0 .. 1023] of Integer;
       VecPtr = ^Vector;

     var
       p, q: VecPtr;

     begin
       GetMem (p, 1024 * SizeOf (Integer));
       q := VecPtr (@p^[512]);

       { ... }

       FreeMem (p, 512 * SizeOf (Integer));

       { ... }

       FreeMem (q, 512 * SizeOf (Integer));
     end.


File: gpc-hr.info,  Node: Operations for Integer and Ordinal Types,  Next: Complex Number Operations,  Prev: Memory Management Routines,  Up: Library Routines

6.10.5 Operations for Integer and Ordinal Types
-----------------------------------------------

   * Bit manipulations: The BP style bit shift operators `shl' and
     `shr' exist in GPC as well as bitwise `and', `or', `xor' and `not'
     for integer values.

          2#100101 and (1 shl 5) = 2#100000

     GPC also supports `and', `or', `xor' and `not' as procedures:

          program BitOperatorProcedureDemo;
          var x: Integer;
          begin
            x := 7;
            and (x, 14);  { sets x to 6 }
            xor (x, 3);   { sets x to 5 }
          end.

   * Succ, Pred: The standard functions `Succ' and `Pred' exist in GPC
     and accept a second parameter.

   * Increment, decrement: The BP built-in Procedures `Inc' and `Dec'
     exist in GPC.

          program IncDecDemo;
          var
            i: Integer;
            c: Char;
          begin
            Inc (i);     { i := i + 1; }
            Dec (i, 7);  { i := i - 7; }
            Inc (c, 3);  { c := Succ (c, 3); }
          end.

   * `Min', `Max': These are a GNU Pascal extension and work for reals
     as well as for ordinal types. Mixing reals and integers is okay,
     the result is real then.



File: gpc-hr.info,  Node: Complex Number Operations,  Next: Set Operations,  Prev: Operations for Integer and Ordinal Types,  Up: Library Routines

6.10.6 Complex Number Operations
--------------------------------

@@ A lot of details missing here

   * binary operators `+', `-', `*', `/' and unary `-', `+'

   * exponentiation operators (`pow' and `**')

   * functions (`Sqr', `SqRt', `Exp', `Ln', `Sin', `Cos', `ArcSin',
     `ArcCos', `ArcTan')

   * number info with `Re', `Im' and `Arg' functions

   * numbers constructed by `Cmplx' or `Polar'

   The following sample programs illustrates most of the `Complex' type
operations.

     program ComplexOperationsDemo (Output);

     var
       z1, z2: Complex;
       Len, Angle: Real;

     begin
       z1 := Cmplx (2, 1);
       WriteLn;
       WriteLn ('Complex number z1 is: (', Re (z1) : 1, ',', Im (z1) : 1, ')');
       WriteLn;
       z2 := Conjugate(z1); { GPC extension }
       WriteLn ('Conjugate of z1 is: (', Re (z2) : 1, ',', Im (z2) : 1, ')');
       WriteLn;
       Len   := Abs (z1);
       Angle := Arg (z1);
       WriteLn ('The polar representation of z1 is: Length=', Len : 1,
                ', Angle=', Angle : 1);
       WriteLn;
       z2 := Polar (Len, Angle);
       WriteLn ('Converting (Length, Angle) back to (x, y) gives: (',
                Re (z2) : 1, ',', Im (z2) : 1, ')');
       WriteLn;
       WriteLn ('The following operations operate on the complex number z1');
       WriteLn;
       z2 := ArcTan (z1);
       WriteLn ('ArcTan (z1) = (', Re (z2), ', ', Im (z2), ')');
       WriteLn;
       z2 := z1 ** 3.141;
       WriteLn ('z1 ** 3.141 =', Re (z2), ', ', Im (z2), ')');
       WriteLn;
       z2 := Sin (z1);
       WriteLn ('Sin (z1) = (', Re (z2), ', ', Im (z2), ')');
       WriteLn ('(Cos, Ln, Exp, SqRt and Sqr exist also.)');
       WriteLn;
       z2 := z1 pow 8;
       WriteLn ('z1 pow 8 = (', Re (z2), ', ', Im (z2), ')');
       WriteLn;
       z2 := z1 pow (-8);
       WriteLn ('z1 pow (-8) = (', Re (z2), ', ', Im (z2), ')');
     end.


File: gpc-hr.info,  Node: Set Operations,  Next: Date And Time Routines,  Prev: Complex Number Operations,  Up: Library Routines

6.10.7 Set Operations
---------------------

GPC supports Standard Pascal set operations. In addition it supports
the Extended Pascal set operation symmetric difference (`set1 >< set2')
operation whose result consists of those elements which are in exactly
one of the operannds.

   It also has a function that counts the elements in the set: `a :=
Card (set1)'.

   In the following description, S1 and S2 are variables of set type, s
is of the base type of the set.

`S1 := S2'
     Assign a set to a set variable.

`S1 + S2'
     Union of sets.

`S1 - S2'
     Difference between two sets.

`S1 * S2'
     Intersection of two sets.

`S1 >< S2'
     Symmetric difference

`S1 = S2'
     Comparison between two sets. Returns boolean result. `True' if
     `S1' has the same elements as `S2'.

`S1 <> S2'
     Comparison between two sets. Returns boolean result. `True' if
     `S1' does not have the same elements as `S2'.

`S1 < S2'

`S2 > S1'
     Comparison between two sets. Returns boolean result. `True' if
     `S1' is a strict subset of `S2'.

`S1 <= S2'

`S2 >= S1'
     Comparison between two sets. Returns boolean result. `True' if
     `S1' is a subset of (or equal to) `S2'.

`s in S1'
     Set membership test between an element `s' and a set. Returns
     boolean result. `True' if `s' is an element of `S1'.

   The following example demonstrates some `set' operations. The results
of the operations are given in the comments.

     program SetOpDemo;

     type
       TCharSet = set of Char;

     var
       S1, S2, S3: TCharSet;
       Result: Boolean;

     begin
       S1 := ['a', 'b', 'c'];
       S2 := ['c', 'd', 'e'];
       S3 := S1 + S2;       { S3 = ['a', 'b', 'c', 'd', 'e'] }
       S3 := S1 * S2;       { S3 = ['c'] }
       S3 := S1 - S2;       { S3 = ['a', 'b'] }
       S3 := S1 >< S2;      { S3 = ['a', 'b', 'd', 'e'] }

       S1 := ['c', 'd', 'e'];
       Result := S1 = S2;   { False }
       Result := S1 < S2;   { False }
       Result := S1 <= S2;  { True }

       S1 := ['c', 'd'];
       Result := S1 <> S2;  { True }
       Result := S2 > S1;   { True }
       Result := S2 >= S1   { True }
     end.


File: gpc-hr.info,  Node: Date And Time Routines,  Prev: Set Operations,  Up: Library Routines

6.10.8 Date And Time Routines
-----------------------------

`procedure GetTimeStamp (var t: TimeStamp);'

`function Date (t: TimeStamp): packed array [1 .. DateLength] of Char;'

`function Time (t: TimeStamp): packed array [1 .. TimeLength] of Char;'

   `DateLength' and `TimeLength' are implementation dependent constants.

   `GetTimeStamp (t)' fills the record `t' with values. If they are
valid, the Boolean flags are set to True.

   `TimeStamp' is a predefined type in the Extended Pascal standard. It
may be extended in an implementation, and is indeed extended in GPC.
For the full definition of `TimeStamp', see *Note TimeStamp::.


File: gpc-hr.info,  Node: Other Languages,  Next: Notes for Debugging,  Prev: Library Routines,  Up: Programming

6.11 Interfacing with Other Languages
=====================================

The standardized GNU compiler back-end makes it relatively easy to
share libraries between GNU Pascal and other GNU compilers. On
Unix-like platforms (_not_ on Dos-like platforms), the GNU compiler
back-end usually complies to the standards defined for that system, so
communication with other compilers should be easy, too.

   In this chapter we discuss how to import libraries written in other
languages, and how to import libraries written in GNU Pascal from other
languages. While the examples will specialize to compatibility to GNU
C, generalization is straightforward if you are familiar with the other
language in question.

* Menu:

* Importing Libraries from Other Languages::
* Exporting GPC Libraries to Other Languages::


File: gpc-hr.info,  Node: Importing Libraries from Other Languages,  Next: Exporting GPC Libraries to Other Languages,  Up: Other Languages

6.11.1 Importing Libraries from Other Languages
-----------------------------------------------

To use a function written in another language, you need to provide an
external declaration for it - either in the program, or in the
interface part of a unit, or a module.

   Let's say you want to use the following C library from Pascal:

     File `callc.c':

     #include <unistd.h>
     #include "callc.h"

     int foo = 1;

     void bar (void)
     {
       sleep (foo);
     }

     File `callc.h':

     /* Actually, we wouldn't need this header file, and could instead
        put these prototypes into callc.c, unless we want to use callc.c
        also from other C source files. */

     extern int foo;
     extern void bar (void);

   Then your program can look like this:

     program CallCDemo;

     {$L callc.c}  { Or: `callc.o' if you don't have the source }

     var
       MyFoo: CInteger; external name 'foo';

     procedure Bar; external name 'bar';

     begin
       MyFoo := 42;
       Bar
     end.

   Or, if you want to provide a `CallCUnit' unit:

     unit CallCUnit;

     interface

     var
       MyFoo: CInteger; external name 'foo';

     procedure Bar; external name 'bar';

     implementation

     {$L callc.c}  { Or: `callc.o' if you don't have the source }

     end.

     program CallCUDemo;

     uses CallCUnit;

     begin
       MyFoo := 42;
       Bar
     end.

   You can either link your program manually with `callc.o' or put a
compiler directive `{$L callc.o}' into your program or unit, and then
GPC takes care of correct linking. If you have the source of the C
library (you always have it if it is Free Software), you can even write
`{$L callc.c}' in the program (like above). Then GPC will also link
with `callc.o', but in addition GPC will run the C compiler whenever
`callc.c' has changed if `--automake' is given, too.

   While it is often convenient, there is no must to give the C
function `bar' the name `Bar' in Pascal; you can name it as you like
(e.g., the variable `MyFoo' has a C name of `foo' in the example above).

   If you omit the `name', the default is the Pascal identifier,
converted to lower-case. So, in this example, the `name' could be
omitted for `Bar', but not for `MyFoo'.

   It is important that data types of both languages are mapped
correctly onto each other. C's `int', for instance, translates to GPC's
`CInteger', and C's `unsigned long' to `MedCard'. For a complete list
of integer types with their C counterparts, see *Note Integer Types::.

   In some cases it can be reasonable to translate a C pointer
parameter to a Pascal `var' parameter.  Since const parameters in GPC
can be passed by value _or_ by reference internally, possibly depending
on the system, `const foo *' parameters to C functions _cannot_
reliably be declared as `const' in Pascal. However, Extended Pascal's
`protected var' can be used since this guarantees passing by reference.

   Some libraries provide a `main' function and require your program's
"main" to be named differently. To achive this with GPC, invoke it with
an option `--gpc-main="GPCmain"' (where `GPCmain' is an example how you
might want to name the program). You can also write it into your source
as a directive `{$gpc-main="GPCmain"}'.


File: gpc-hr.info,  Node: Exporting GPC Libraries to Other Languages,  Prev: Importing Libraries from Other Languages,  Up: Other Languages

6.11.2 Exporting GPC Libraries to Other Languages
-------------------------------------------------

The `.o' files produced by GPC are in the same format as those of all
other GNU compilers, so there is no problem in writing libraries for
other languages in Pascal. To use them, you will need to write kind of
interface - a header file in C. However there are some things to take
into account, especially if your Pascal unit exports objects:

   * By default, GPC capitalizes the first letter (only) of each
     identifier, so `procedure FooBAR' must be imported as `extern void
     Foobar()' from C.

   * If you want to specify the external name explicitly, use
     `attribute':

          procedure FooBAR; attribute (name = 'FooBAR');
          begin
            WriteLn ('FooBAR')
          end;

     This one can be imported from C with `extern void FooBar()'.

   * Objects are "records" internally.  They have an implicit `vmt'
     field which contains a pointer to the "virtual method table".
     This table is another record of the following structure:

          type
            VMT = record
              ObjectSize: PtrInt;     { Size of object in bytes }
              NegObjectSize: PtrInt;  { Negated size }
              Methods: array [1 .. n] of procedure;
                { Pointers to the virtual methods. The entries are of the
                   repective procedure or function types. }
            end;

     You can call a virtual method of an object from C if you explicitly
     declare this `struct' and explicitly dereference the `Fun' array.
     The VMT of an object `FooBAR' is an external (in C sense) variable
     `vmt_Foobar' internally.

   * Methods of objects are named `Myobject_Mymethod' (with exactly two
     capital letters) internally.

   * If you want to put a program in a library for some reason, and you
     want to give the `main' program an internal name different from
     `main', call GPC with the command-line option
     `--gpc-main="GPCmain"' (see the previous subsection).



File: gpc-hr.info,  Node: Notes for Debugging,  Next: I18N,  Prev: Other Languages,  Up: Programming

6.12 Notes for Debugging
========================

   * The GNU debugger, `gdb', does not yet understand Pascal sets,
     files or subranges. Now `gdb' allows you to debug these things,
     even though it does not yet understand some stabs.

   * Forward referencing pointers generate debug info that appears as
     generic pointers.

   * No information of `with' statements is currently given to the
     debugger.

   * When debugging, please note that the Initial Letter In Each
     Identifier Is In Upper Case And The Rest Are In Lower Case, unless
     explicitly overriden with `name' (*note name::). This is to reduce
     name clashes with libc and other possible libraries.

   * All visible GPC Run Time System routines have linker names starting
     with `_p_'.

   * The linker name of the main program is `pascal_main_program'.
     This is done because ISO Standard wants to have the program name in
     a separate name space.


File: gpc-hr.info,  Node: I18N,  Next: Run Time System,  Prev: Notes for Debugging,  Up: Programming

6.13 How to use I18N in own programs
====================================

This chapter discusses shortly how to use the Internationalization
(I18N) features of GNU Pascal.

Prerequisite
------------

You need to have gettext installed. Try to compile
`demos/gettextdemo.pas'. Furthermore, you should download a tool named
`pas2po' from `http://www.gnu-pascal.org/contrib/eike/'.

The source
----------

We would like to translate the messages provided with this simple
example different languages (here: German) without touching the source
for each language:

     program Hello1;

     begin
       WriteLn ('Hello, World!');
       WriteLn ('The answer of the questions is: ', 42)
     end.

Preparing the source
--------------------

To do so, we must prepare the source to use gettext:

     program Hello2;

     uses GPC, Intl;

     var s: TString;

     begin
       Discard (BindTextDomain ('hello2', '/usr/share/locale/'));
       Discard (TextDomain ('hello2'));
       WriteLn (GetText ('Hello, World!'));
       s := FormatString (GetText ('The answer of the questions is %s'), 42);
       WriteLn (s)
     end.

   `BindTextDomain' sets the path to find our message catalogs in the
system. This path is system dependent. `TextDomain' tells the program
to use this catalog. `GetText' looks up the given string in the catalog
and returns a translated string within the current locale settings.
`FormatString' replaces some format specifiers with the following
argument. `%s' is the first following argument. After this step is
done, we do not need to touch the sourcefile any longer. The output of
this program is as follows:

     Hello, World!
     The answer of the questions is 42

Getting the translatable strings
--------------------------------

There are lots of strings in the above example, but only those
surrounded with `GetText' should be translated. We use `pas2po
hello2.pas -o hello2.po' to extract the messages. The output is:

     # This file was created by pas2po with 'hello2.pas'.
     # Please change this file manually.
     # SOME DESCRIPTIVE TITLE.
     # Copyright (C) YEAR Free Software Foundation, Inc.
     # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
     #
     #, fuzzy
     msgid ""
     msgstr ""
     "Project-Id-Version: PACKAGE VERSION\n"
     "POT-Creation-Date: 2003-04-27 20:48+0200\n"
     "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
     "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
     "Language-Team: LANGUAGE <LL@li.org>\n"
     "MIME-Version: 1.0\n"
     "Content-Type: text/plain; charset=CHARSET\n"
     "Content-Transfer-Encoding: 8bit\n"

     #hello2.pas:10
     msgid "Hello, World!"
     msgstr ""

     #hello2.pas:11
     msgid "The answer of the questions is %s"
     msgstr ""

   Now we translate the message ids into German language, and set some
needful informations at their appropriate places. The following steps
must be repeated for each language we would like to support:

     # This file was created by pas2po with 'hello2.pas'.
     # Copyright (C) 2003 Free Software Foundation, Inc.
     # Eike Lange  <eike@g-n-u.de>, 2003.
     msgid ""
     msgstr ""
     "Project-Id-Version: Hello2 1.0\n"
     "POT-Creation-Date: 2003-04-27 12:00+0200\n"
     "PO-Revision-Date: 2003-04-27 12:06+0200\n"
     "Last-Translator: Eike Lange <eike@g-n-u.de>\n"
     "Language-Team: de <de@li.org>\n"
     "MIME-Version: 1.0\n"
     "Content-Type: text/plain; charset=ISO-8859-1\n"
     "Content-Transfer-Encoding: 8bit\n"

     #hello2.pas:10
     msgid "Hello, World!"
     msgstr "Hallo, Welt!"

     #hello2.pas:11
     msgid "The answer of the questions is %s"
     msgstr "'%s' lautet die Antwort auf die Frage."

   Please note that we swapped text and numeric arguments and added
some single quotes arround the first argument. We compile the message
catalog with `msgfmt -vv hello2.po -o hello2.mo' and install the file
`hello2.mo' at `/usr/share/locale/de/LC_MESSAGES/' With a german locale
setting, the output should be as follows:

     Hallo, Welt!
     '42' lautet die Antwort auf die Frage.

System dependent notes:
-----------------------

The topmost path where message catalogs reside is system dependent:

for DJGPP:
     `GetEnv ('$DJDIR') + '/share/locale''

for Mac OS X:
     `/usr/share/locale' or `/sw/share/locale'

for Linux, *BSD:
     `/usr/share/locale' or `/usr/local/share/locale'

See also
--------

*Note Gettext: (gettext)Gettext, *Note FormatString::, *Note Intl::.

