prog.tex 250 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847
  1. %
  2. % $Id$
  3. % This file is part of the FPC documentation.
  4. % Copyright (C) 1997, by Michael Van Canneyt
  5. %
  6. % The FPC documentation is free text; you can redistribute it and/or
  7. % modify it under the terms of the GNU Library General Public License as
  8. % published by the Free Software Foundation; either version 2 of the
  9. % License, or (at your option) any later version.
  10. %
  11. % The FPC Documentation is distributed in the hope that it will be useful,
  12. % but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. % Library General Public License for more details.
  15. %
  16. % You should have received a copy of the GNU Library General Public
  17. % License along with the FPC documentation; see the file COPYING.LIB. If not,
  18. % write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  19. % Boston, MA 02111-1307, USA.
  20. %
  21. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  22. % Preamble.
  23. \input{preamble.inc}
  24. \latex{%
  25. \ifpdf
  26. \pdfinfo{/Author(Michael Van Canneyt)
  27. /Title(Programmers' Guide)
  28. /Subject(Free Pascal Programmers' guide)
  29. /Keywords(Free Pascal)
  30. }
  31. \fi
  32. }
  33. %
  34. % Settings
  35. %
  36. \makeindex
  37. \FPCexampledir{progex}
  38. %
  39. % Start of document.
  40. %
  41. \begin{document}
  42. \title{Free Pascal \\ Programmers' manual}
  43. \docdescription{Programmers' manual for \fpc, version \fpcversion}
  44. \docversion{1.9}
  45. \input{date.inc}
  46. \author{Micha\"el Van Canneyt}
  47. \maketitle
  48. \tableofcontents
  49. \newpage
  50. \listoftables
  51. \newpage
  52. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  53. % Introduction
  54. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  55. \section*{About this document}
  56. This is the programmer's manual for \fpc.
  57. It describes some of the peculiarities of the \fpc compiler, and provides a
  58. glimpse of how the compiler generates its code, and how you can change the
  59. generated code. It will not, however, provide a detailed account of
  60. the inner workings of the compiler, nor will it describe how to use the
  61. compiler (described in the \userref). It also will not describe the inner
  62. workings of the Run-Time Library (RTL). The best way to learn about the way
  63. the RTL is implemented is from the sources themselves.
  64. The things described here are useful when things need to be done that
  65. require greater flexibility than the standard Pascal language constructs
  66. (described in the \refref).
  67. Since the compiler is continuously under development, this document may get
  68. out of date. Wherever possible, the information in this manual will be
  69. updated. If you find something which isn't correct, or you think something
  70. is missing, feel free to contact me\footnote{at
  71. \var{[email protected]}}.
  72. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  73. % Compiler switches
  74. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  75. \chapter{Compiler directives}
  76. \label{ch:CompSwitch}
  77. \fpc supports compiler directives in the source file. They are not the same
  78. as Turbo Pascal directives, although some are supported for compatibility.
  79. There is a distinction between local and global directives; local directives
  80. take effect from the moment they are encountered, global directives have an
  81. effect on all of the compiled code.
  82. Many switches have a long form also. If they do, then the name of the
  83. long form is given also. For long switches, the + or - character to switch
  84. the option on or off, may be replaced by \var{ON} or \var{OFF} keywords.
  85. Thus \verb|{$I+}| is equivalent to \verb|{$IOCHECKS ON}| or
  86. \verb|{$IOCHECKS +}| and
  87. \verb|{$C-}| is equivalent to \verb|{$ASSERTIONS OFF}| or
  88. \verb|{$ASSERTIONS -}|
  89. The long forms of the switches are the same as their Delphi
  90. counterparts.
  91. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  92. % Local switches
  93. \section{Local directives}
  94. \label{se:LocalSwitch}
  95. Local directives can occur more than once in a unit or program,
  96. If they have a command-line counterpart, the command-line argument is
  97. restored as the default for each compiled file. The local directives
  98. influence the compiler's behaviour from the moment they're encountered
  99. until the moment another switch annihilates their behaviour, or the end
  100. of the current unit or program is reached.
  101. \subsection{\var{\$A} or \var{\$ALIGN} : Align Data}
  102. This switch is recognized for Turbo Pascal Compatibility, but is not
  103. yet implemented. The alignment of data will be different in any case.
  104. \subsection{\var{\$ASMMODE} : Assembler mode (Intel 80x86 only)}
  105. \label{se:AsmReader}
  106. The \var{\{\$ASMMODE XXX\}} directive informs the compiler what kind of assembler
  107. it can expect in an \var{asm} block. The \var{XXX} should be replaced by one
  108. of the following:
  109. \begin{description}
  110. \item [att\ ] Indicates that \var{asm} blocks contain AT\&T syntax assembler.
  111. \item [intel\ ] Indicates that \var{asm} blocks contain Intel syntax
  112. assembler.
  113. \item [direct\ ] Tells the compiler that asm blocks should be copied
  114. directly to the assembler file.
  115. \end{description}
  116. These switches are local, and retain their value to the end of the unit that
  117. is compiled, unless they are replaced by another directive of the same type.
  118. The command-line switch that corresponds to this switch is \var{-R}.
  119. The default assembler reader is the AT\&T reader.
  120. \subsection{\var{\$B} or \var{\$BOOLEVAL} : Complete boolean evaluation}
  121. This switch is understood by the \fpc compiler, but is ignored. The compiler
  122. always uses shortcut evaluation, i.e. the evaluation of a boolean expression
  123. is stopped once the result of the total exression is known with certainty.
  124. So, in the following example, the function \var{Bofu}, which has a boolean
  125. result, will never get called.
  126. \begin{verbatim}
  127. If False and Bofu then
  128. ...
  129. \end{verbatim}
  130. This has as a consequence that any additional actions that are done by
  131. \var{Bofu} are not executed.
  132. \subsection{\var{\$C} or \var{\$ASSERTIONS} : Assertion support}
  133. The \var{\{\$ASSERTIONS\}} switch determines if assert statements are
  134. compiled into the binary or not. If the switch is on, the statement
  135. \begin{verbatim}
  136. Assert(BooleanExpression,AssertMessage);
  137. \end{verbatim}
  138. Will be compiled in the binary. If te \var{BooleanExpression} evaluates to
  139. \var{False}, the RTL will check if the \var{AssertErrorProc} is set. If it
  140. is set, it will be called with as parameters the \var{AssertMessage}
  141. message, the name of the file, the LineNumber and the address. If it is not
  142. set, a runtime error 227 is generated.
  143. The \var{AssertErrorProc} is defined as
  144. \begin{verbatim}
  145. Type
  146. TAssertErrorProc=procedure(const msg,fname:string;lineno,erroraddr:longint);
  147. Var
  148. AssertErrorProc = TAssertErrorProc;
  149. \end{verbatim}
  150. This can be used mainly for debugging purposes. The \file{system} unit sets the
  151. \var{AssertErrorProc} to a handler that displays a message on \var{stderr}
  152. and simply exits. The \file{sysutils} unit catches the run-time error 227
  153. and raises an \var{EAssertionFailed} exception.
  154. \subsection{\var{\$DEFINE} : Define a symbol}
  155. The directive
  156. \begin{verbatim}
  157. {$DEFINE name}
  158. \end{verbatim}
  159. defines the symbol \var{name}. This symbol remains defined until the end of
  160. the current module (i.e. unit or program), or until a \var{\$UNDEF name} directive is encountered.
  161. If \var{name} is already defined, this has no effect. \var{Name} is case
  162. insensitive.
  163. The symbols that are defined in a unit, are not saved in the unit file,
  164. so they are also not exported from a unit.
  165. \subsection{\var{\$ELSE} : Switch conditional compilation}
  166. The \var{\{\$ELSE\}} switches between compiling and ignoring the source
  167. text delimited by the preceding \var{\{\$IFxxx\}} and following
  168. \var{\{\$ENDIF\}}. Any text after the \var{ELSE} keyword but before the
  169. brace is ignored:
  170. \begin{verbatim}
  171. {$ELSE some ignored text}
  172. \end{verbatim}
  173. is the same as
  174. \begin{verbatim}
  175. {$ELSE}
  176. \end{verbatim}
  177. This is useful for indication what switch is meant.
  178. \subsection{\var{\$ENDIF} : End conditional compilation}
  179. The \var{\{\$ENDIF\}} directive ends the conditional compilation initiated by the
  180. last \var{\{\$IFxxx\}} directive. Any text after the \var{ENDIF} keyword but
  181. before the closing brace is ignored:
  182. \begin{verbatim}
  183. {$ENDIF some ignored text}
  184. \end{verbatim}
  185. is the same as
  186. \begin{verbatim}
  187. {$ENDIF}
  188. \end{verbatim}
  189. This is useful for indication what switch is meant to be ended.
  190. \subsection{\var{\$ERROR} : Generate error message}
  191. The following code
  192. \begin{verbatim}
  193. {$ERROR This code is erroneous !}
  194. \end{verbatim}
  195. will display an error message when the compiler encounters it,
  196. and increase the error count of the compiler.
  197. The compiler will continue to compile, but no code will be emitted.
  198. \subsection{\var{\$F} : Far or near functions}
  199. This directive is recognized for compatibility with Turbo Pascal. Under the
  200. 32-bit and 64-bit programming models, the concept of near and far calls have
  201. no meaning, hence the directive is ignored. A warning is printed to the screen,
  202. as a reminder.
  203. As an example, the following piece of code:
  204. \begin{verbatim}
  205. {$F+}
  206. Procedure TestProc;
  207. begin
  208. Writeln ('Hello From TestProc');
  209. end;
  210. begin
  211. testProc
  212. end.
  213. \end{verbatim}
  214. Generates the following compiler output:
  215. \begin{verbatim}
  216. malpertuus: >pp -vw testf
  217. Compiler: ppc386
  218. Units are searched in: /home/michael;/usr/bin/;/usr/lib/ppc/0.9.1/linuxunits
  219. Target OS: Linux
  220. Compiling testf.pp
  221. testf.pp(1) Warning: illegal compiler switch
  222. 7739 kB free
  223. Calling assembler...
  224. Assembled...
  225. Calling linker...
  226. 12 lines compiled,
  227. 1.00000000000000E+0000
  228. \end{verbatim}
  229. One can see that the verbosity level was set to display warnings.
  230. When declaring a function as \var{Far} (this has the same effect as setting it
  231. between \var{\{\$F+\} \dots \{\$F-\}} directives), the compiler also generates a
  232. warning:
  233. \begin{verbatim}
  234. testf.pp(3) Warning: FAR ignored
  235. \end{verbatim}
  236. The same story is true for procedures declared as \var{Near}. The warning
  237. displayed in that case is:
  238. \begin{verbatim}
  239. testf.pp(3) Warning: NEAR ignored
  240. \end{verbatim}
  241. \subsection{\var{\$FATAL} : Generate fatal error message}
  242. The following code
  243. \begin{verbatim}
  244. {$FATAL This code is erroneous !}
  245. \end{verbatim}
  246. will display an error message when the compiler encounters it,
  247. and the compiler will immediatly stop the compilation process.
  248. This is mainly useful inc conjunction wih \var{\{\$IFDEF\}} or
  249. \var{\{\$IFOPT\}} statements.
  250. \subsection{\var{\$GOTO} : Support \var{Goto} and \var{Label}}
  251. If \var{\{\$GOTO ON\}} is specified, the compiler will support \var{Goto}
  252. statements and \var{Label} declarations. By default, \var{\$GOTO OFF} is
  253. assumed. This directive corresponds to the \var{-Sg} command-line option.
  254. As an example, the following code can be compiled:
  255. \begin{verbatim}
  256. {$GOTO ON}
  257. label Theend;
  258. begin
  259. If ParamCount=0 then
  260. GoTo TheEnd;
  261. Writeln ('You specified command-line options');
  262. TheEnd:
  263. end.
  264. \end{verbatim}
  265. \begin{remark}When compiling assembler code using the inline assembler
  266. readers, any labels used in the assembler code must be declared, and
  267. the \var{\{\$GOTO ON\}} directive should be used.
  268. \end{remark}
  269. \subsection{\var{\$H} or \var{\$LONGSTRINGS} : Use AnsiStrings}
  270. If \var{\{\$LONGSTRINGS ON\}} is specified, the keyword \var{String} (no
  271. length specifier) will be treated as \var{AnsiString}, and the compiler
  272. will treat the corresponding variable as an ansistring, and will
  273. generate corresponding code.
  274. By default, the use of ansistrings is off, corresponding to \var{\{\$H-\}}.
  275. The \file{system} unit is compiled without ansistrings, all its functions accept
  276. shortstring arguments. The same is true for all RTL units, except the
  277. \file{sysutils} unit, which is compiled with ansistrings.
  278. \subsection{\var{\$HINT} : Generate hint message}
  279. If the generation of hints is turned on, through the \var{-vh} command-line
  280. option or the \var{\{\$HINTS ON\}} directive, then
  281. \begin{verbatim}
  282. {$Hint This code should be optimized }
  283. \end{verbatim}
  284. will display a hint message when the compiler encounters it.
  285. By default, no hints are generated.
  286. \subsection{\var{\$HINTS} : Emit hints}
  287. \var{\{\$HINTS ON\}} switches the generation of hints on.
  288. \var{\{\$HINTS OFF\}} switches the generation of hints off.
  289. Contrary to the command-line option \var{-vh} this is a local switch,
  290. this is useful for checking parts of the code.
  291. \subsection{\var{\$IF} : Start conditional compilation}
  292. The directive \var{\{\$IF expr\}} will continue the compilation
  293. if the boolean expression \var{expr} evaluates to \var{true}. If the
  294. compilation evaluates to false, then the source is skipped to the first
  295. \var{\{\$ELSE\}} or \var{\{\$ENDIF\}} directive.
  296. The compiler must be able to evaluate the expression at parse time.
  297. This means that variables or constants that are defined in
  298. the source cannot be used. Macros and symbols may be used, however.
  299. More information on this can be found in the section about
  300. conditionals.
  301. \subsection{\var{\$IFDEF Name} : Start conditional compilation}
  302. If the symbol \var{Name} is not defined then the \var{\{\$IFDEF name\}}
  303. will skip the compilation of the text that follows it to the first
  304. \var{\{\$ELSE\}} or \var{\{\$ENDIF\}} directive.
  305. If \var{Name} is defined, then compilation continues as if the directive
  306. wasn't there.
  307. \subsection{\var{\$IFNDEF} : Start conditional compilation}
  308. If the symbol \var{Name} is defined then the \var{\{\$IFNDEF name\}}
  309. will skip the compilation of the text that follows it to the first
  310. \var{\{\$ELSE\}} or \var{\{\$ENDIF\}} directive.
  311. If it is not defined, then compilation continues as if the directive
  312. wasn't there.
  313. \subsection{\var{\$IFOPT} : Start conditional compilation}
  314. The \var{\{\$IFOPT switch\}} will compile the text that follows it if the
  315. switch \var{switch} is currently in the specified state.
  316. If it isn't in the specified state, then compilation continues after the
  317. corresponding \var{\{\$ELSE\}} or \var{\{\$ENDIF\}} directive.
  318. As an example:
  319. \begin{verbatim}
  320. {$IFOPT M+}
  321. Writeln ('Compiled with type information');
  322. {$ENDIF}
  323. \end{verbatim}
  324. Will compile the writeln statement if generation of type information is on.
  325. \begin{remark}The \var{\{\$IFOPT\}} directive accepts only short options,
  326. i.e. \var{\{\$IFOPT TYPEINFO\}} will not be accepted.
  327. \end{remark}
  328. \subsection{\var{\$INFO} : Generate info message}
  329. If the generation of info is turned on, through the \var{-vi} command-line
  330. option, then
  331. \begin{verbatim}
  332. {$INFO This was coded on a rainy day by Bugs Bunny}
  333. \end{verbatim}
  334. will display an info message when the compiler encounters it.
  335. This is useful in conjunction with the \var{\{\$IFDEF\}} directive, to show
  336. information about which part of the code is being compiled.
  337. \subsection{\var{\$INLINE} : Allow inline code.}
  338. The \var{\{\$INLINE ON\}} directive tells the compiler that the \var{Inline}
  339. procedure modifier should be allowed. Procedures that are declared inline
  340. are copied to the places where they are called. This has the effect that
  341. there is no actual procedure call, the code of the procedure is just copied
  342. to where the procedure is needed, this results in faster execution speed if
  343. the function or procedure is used a lot.
  344. By default, \var{Inline} procedures are not allowed. This directive must be
  345. specified to use inlined code. The directive is equivalent to the command-line
  346. switch \var{-Si}. For more information on inline routines, consult the \refref.
  347. \subsection{\var{\$I} or \var{\$IOCHECKS} : Input/Output checking}
  348. The \var{\{\$I-\}} or \var{\{\$IOCHECKS OFF\}} directive tells the compiler
  349. not to generate input/output checking code in the program. By default, the
  350. compiler does not generate this code, it must be switched on using the \var{-Ci}
  351. command-line switch.
  352. When compiling using the \var{-Ci} compiler switch, the \fpc compiler inserts
  353. input/output checking code after every input/output call in the code.
  354. If an error occurred during input or output, then a run-time error will
  355. be generated. Use this switch to avoid this behaviour.
  356. To check if something went wrong, the \var{IOResult} function can be used
  357. to see if everything went without problems.
  358. Conversely, \var{\{\$I+\}} will turn error-checking back on, until another
  359. directive is encountered which turns it off again.
  360. The most common use for this switch is to check if the opening of a file
  361. went without problems, as in the following piece of code:
  362. \begin{verbatim}
  363. assign (f,'file.txt');
  364. {$I-}
  365. rewrite (f);
  366. {$I+}
  367. if IOResult<>0 then
  368. begin
  369. Writeln ('Error opening file: "file.txt"');
  370. exit
  371. end;
  372. \end{verbatim}
  373. See the \var{IOResult} function explanation in \refref for a
  374. detailed description of the possible errors that can occur when using
  375. input/output checking.
  376. \subsection{\var{\$I} or \var{\$INCLUDE} : Include file }
  377. The \var{\{\$I filename\}} or \var{\{\$INCLUDE filename\}} directive
  378. tells the compiler to read further statements from the file \var{filename}.
  379. The statements read there will be inserted as if they occurred in the
  380. current file.
  381. The compiler will append the \file{.pp} extension to the file if no
  382. extension is given. Do not put the filename between quotes, as
  383. they will be regarded as part of the file's name.
  384. Include files can be nested, but not infinitely deep. The number of files is
  385. restricted to the number of file descriptors available to the \fpc compiler.
  386. Contrary to Turbo Pascal, include files can cross blocks. I.e.
  387. a block can start in one file (with a \var{Begin} keyword) and can end in another (with
  388. a \var{End} keyword). The smallest entity in an include file must be a token,
  389. i.e. an identifier, keyword or operator.
  390. The compiler will look for the file to include in the following places:
  391. \begin{enumerate}
  392. \item It will look in the path specified in the include file name.
  393. \item It will look in the directory where the current source file is.
  394. \item it will look in all directories specified in the include file search
  395. path.
  396. \end{enumerate}
  397. Directories can be added to the include file search path with the \var{-I}
  398. command-line option.
  399. \subsection{\var{\$I} or \var{\$INCLUDE} : Include compiler info}
  400. In this form:
  401. \begin{verbatim}
  402. {$INCLUDE %xxx%}
  403. \end{verbatim}
  404. where \var{xxx} is one of \var{TIME}, \var{DATE}, \var{FPCVERSION} or
  405. \var{FPCTARGET}, will generate a macro with the value of these things.
  406. If \var{xxx} is none of the above, then it is assumed to be the value of
  407. an environment variable. It's value will be fetched, and inserted in the code
  408. as if it were a string.
  409. For example, the following program
  410. \begin{verbatim}
  411. Program InfoDemo;
  412. Const User = {$I %USER%};
  413. begin
  414. Write ('This program was compiled at ',{$I %TIME%});
  415. Writeln (' on ',{$I %DATE%});
  416. Writeln ('By ',User);
  417. Writeln ('Compiler version: ',{$I %FPCVERSION%});
  418. Writeln ('Target CPU: ',{$I %FPCTARGET%});
  419. end.
  420. \end{verbatim}
  421. Creates the following output:
  422. \begin{verbatim}
  423. This program was compiled at 17:40:18 on 1998/09/09
  424. By michael
  425. Compiler version: 0.99.7
  426. Target CPU: i386
  427. \end{verbatim}
  428. % Assembler type
  429. \subsection{\var{\$I386\_XXX} : Specify assembler format (Intel 80x86 only)}
  430. This switch selects the assembler reader. \var{\{\$I386\_XXX\}}
  431. has the same effect as \var{\{\$ASMMODE XXX\}}, \sees{AsmReader}
  432. This switch is deprecated, the \var{\{\$ASMMODE XXX\}} directive should
  433. be used instead.
  434. \subsection{\var{\$L} or \var{\$LINK} : Link object file}
  435. The \var{\{\$L filename\}} or \var{\{\$LINK filename\}} directive
  436. tells the compiler that the file \file{filename} should be linked to
  437. the program. This cannot be used for libraries, see section
  438. \sees{linklib} for that.
  439. The compiler will look for this file in the following way:
  440. \begin{enumerate}
  441. \item It will look in the path specified in the object file name.
  442. \item It will look in the directory where the current source file is.
  443. \item it will look in all directories specified in the object file search path.
  444. \end{enumerate}
  445. Directories can be added to the object file search path with the \var{-Fo}
  446. option.
  447. On \linux systems and on operating systems with case-sensitive filesystems
  448. (such as \unix systems), the name is case sensitive, and must be typed
  449. exactly as it appears on your system.
  450. \begin{remark}Take care that the object file you're linking is in a
  451. format the linker understands. Which format this is, depends on the platform
  452. you're on. Typing \var{ld} or \var{ld --help} on the command line gives a list of formats
  453. \var{ld} knows about.
  454. \end{remark}
  455. Other files and options can be passed to the linker using the \var{-k}
  456. command-line option. More than one of these options can be used, and
  457. they will be passed to the linker, in the order that they were specified on
  458. the command line, just before the names of the object files that must be
  459. linked.
  460. \subsection{\var{\$LINKLIB} : Link to a library}
  461. \label{se:linklib}
  462. The \var{\{\$LINKLIB name\}} will link to a library \file{name}.
  463. This has the effect of passing \var{-lname} to the linker.
  464. As an example, consider the following unit:
  465. \begin{verbatim}
  466. unit getlen;
  467. interface
  468. {$LINKLIB c}
  469. function strlen (P : pchar) : longint;cdecl;
  470. implementation
  471. function strlen (P : pchar) : longint;cdecl;external;
  472. end.
  473. \end{verbatim}
  474. If one would issue the command
  475. \begin{verbatim}
  476. ppc386 foo.pp
  477. \end{verbatim}
  478. where foo.pp has the above unit in its \var{uses} clause,
  479. then the compiler would link the program to the c library, by passing the
  480. linker the \var{-lc} option.
  481. The same effect could be obtained by removing the linklib directive in the
  482. above unit, and specify \var{-k-lc} on the command-line:
  483. \begin{verbatim}
  484. ppc386 -k-lc foo.pp
  485. \end{verbatim}
  486. \subsection{\var{\$M} or \var{\$TYPEINFO} : Generate type info}
  487. For classes that are compiled in the \var{\{\$M+\}} or \var{\{\$TYPEINFO ON\}}
  488. state, the compiler will generate Run-Time Type Information (RTTI). All
  489. descendent objects of an object that was compiled in the \var{\{\$M+\}} state
  490. will get RTTI information too, as well as any published classes.
  491. By default, no Run-Time Type Information is generated. The \var{TPersistent}
  492. object that is present in the FCL (Free Component Library) is generated in
  493. the \var{\{\$M+\}} state. The generation of RTTI allows programmers to
  494. stream objects, and to access published properties of objects, without
  495. knowing the actual class of the object.
  496. The run-time type information is accessible through the \var{TypInfo} unit,
  497. which is part of the \fpc Run-Time Library.
  498. \begin{remark}
  499. The streaming system implemented by \fpc requires that all
  500. streamable components be descendent from \var{TPersistent}.
  501. \end{remark}
  502. \subsection{\var{\$MACRO} : Allow use of macros.}
  503. In the \var{\{\$MACRO ON\}} state, the compiler allows to use C-style
  504. (although not as elaborate) macros. Macros provide a means for simple text
  505. substitution. More information on using macros can be found in the
  506. \sees{Macros} section. This directive is equivalent to the command-line
  507. switch \var{-Sm}.
  508. By default, macros are not allowed.
  509. \subsection{\var{\$MAXFPUREGISTERS} : Maximum number of FPU registers for variables (Intel 80x86 only)}
  510. The \var{\{\$MAXFPUREGISTERS XXX\}} directive tells the compiler how much floating point
  511. variables can be kept in the floating point processor registers. This switch is ignored
  512. unless the \var{-Or} (use register variables) optimization is used.
  513. This is quite tricky because the Intel FPU stack is limited to 8 entries.
  514. The compiler uses a heuristic algorithm to determine how much variables should be
  515. put onto the stack: in leaf procedures it is limited to 3 and in non leaf
  516. procedures to 1. But in case of a deep call tree or, even worse, a recursive
  517. procedure this can still lead to a FPU stack overflow, so the user can tell
  518. the compiler how much (floating point) variables should be kept in registers.
  519. The directive accepts the following arguments:
  520. \begin{description}
  521. \item [N] where \var{N} is the maximum number of FPU registers to use.
  522. Currently this can be in the range 0 to 7.
  523. \item[Normal] restores the heuristic and standard behavior.
  524. \item[Default] restores the heuristic and standard behaviour.
  525. \end{description}
  526. \begin{remark}This directive is valid until the end of the current procedure.
  527. \end{remark}
  528. \subsection{\var{\$MESSAGE} : Generate info message}
  529. If the generation of info is turned on, through the \var{-vi} command-line
  530. option, then
  531. \begin{verbatim}
  532. {$MESSAGE This was coded on a rainy day by Bugs Bunny }
  533. \end{verbatim}
  534. will display an info message when the compiler encounters it. The effect is
  535. the same as the \var{\{\$INFO\}} directive.
  536. \subsection{\var{\$MMX} : Intel MMX support (Intel 80x86 only)}
  537. \fpc supports optimization for the \textbf{MMX} Intel
  538. processor (see also chapter \ref{ch:MMXSupport}).
  539. This optimizes certain code parts for the \textbf{MMX} Intel
  540. processor, thus greatly improving speed. The speed is noticed mostly when
  541. moving large amounts of data. Things that change are
  542. \begin{itemize}
  543. \item Data with a size that is a multiple of 8 bytes is moved using the
  544. \var{movq} assembler instruction, which moves 8 bytes at a time
  545. \end{itemize}
  546. \begin{remark}MMX support is NOT emulated on non-MMX systems, i.e. if
  547. the processor doesn't have the MMX extensions, the MMX optimizations cannot
  548. be used.
  549. \end{remark}
  550. When \textbf{MMX} support is on, it is not allowed to do floating point
  551. arithmetic. It is allowed to move floating point data, but no arithmetic
  552. can be done. If floating point math must be done anyway, first \textbf{MMX}
  553. support must be switched off and the FPU must be cleared using the \var{emms}
  554. function of the \file{cpu} unit.
  555. The following example will make this more clear:
  556. \begin{verbatim}
  557. Program MMXDemo;
  558. uses mmx;
  559. var
  560. d1 : double;
  561. a : array[0..10000] of double;
  562. i : longint;
  563. begin
  564. d1:=1.0;
  565. {$mmx+}
  566. { floating point data is used, but we do _no_ arithmetic }
  567. for i:=0 to 10000 do
  568. a[i]:=d2; { this is done with 64 bit moves }
  569. {$mmx-}
  570. emms; { clear fpu }
  571. { now we can do floating point arithmetic }
  572. ...
  573. end.
  574. \end{verbatim}
  575. See, however, the chapter on MMX (\ref{ch:MMXSupport}) for more information
  576. on this topic.
  577. \subsection{\var{\$NOTE} : Generate note message}
  578. If the generation of notes is turned on, through the \var{-vn} command-line
  579. option or the \var{\{\$NOTES ON\}} directive, then
  580. \begin{verbatim}
  581. {$NOTE Ask Santa Claus to look at this code}
  582. \end{verbatim}
  583. will display a note message when the compiler encounters it.
  584. \subsection{\var{\$NOTES} : Emit notes}
  585. \var{\{\$NOTES ON\}} switches the generation of notes on.
  586. \var{\{\$NOTES OFF\}} switches the generation of notes off.
  587. Contrary to the command-line option \var{-vn} this is a local switch,
  588. this is useful for checking parts of the code.
  589. By default, \var{\{\$NOTES\}} is off.
  590. \subsection{\var{\$OUTPUT\_FORMAT} : Specify the output format}
  591. \var{\{\$OUTPUT\_FORMAT format\}} has the same functionality as the \var{-A}
  592. command-line option: it tells the compiler what kind of object file must be
  593. generated. You can specify this switch only {\em before} the \var{Program}
  594. or \var{Unit} clause in your source file. The different kinds of formats are
  595. shown in \seet{Formats}.
  596. The default output format depends on the platform the compiler was compiled
  597. on.
  598. \begin{FPCltable}{ll}{Formats generated by the x86 compiler}{Formats} \hline
  599. Switch value & Generated format \\ \hline
  600. AS & AT\&T assembler file. \\
  601. AS\_AOUT & Go32v1 assembler file.\\
  602. ASW & AT\&T Win32 assembler file. \\
  603. COFF & Go32v2 COFF object file.\\
  604. MASM & Masm assembler file.\\
  605. NASM & Nasm assembler file.\\
  606. NASMCOFF & Nasm assembler file (COFF format).\\
  607. NASMELF & Nasm assembler file (ELF format).\\
  608. PECOFF & PECOFF object file (Win32).\\
  609. TASM & Tasm assembler file.\\
  610. \end{FPCltable}
  611. \subsection{\var{\$P} or \var{\$OPENSTRINGS} : Use open strings}
  612. If this switch is on, all function or procedure parameters of type string
  613. are considered to be open string parameters; this parameter only has effect
  614. for short strings, not for ansistrings.
  615. When using openstrings, the declared type of the string can be different
  616. from the type of string that is actually passed, even for strings that are
  617. passed by reference. The declared size of the string passed can be examined
  618. with the \var{High(P)} call.
  619. Default the use of openstrings is off.
  620. \subsection{\var{\$PACKENUM} : Minimum enumeration type size}
  621. This directive tells the compiler the minimum number of bytes it should
  622. use when storing enumerated types. It is of the following form:
  623. \begin{verbatim}
  624. {$PACKENUM xxx}
  625. {$MINENUMSIZE xxx}
  626. \end{verbatim}
  627. Where the form with \var{\$MINENUMSIZE} is for Delphi compatibility.
  628. \var{xxx} can be one of \var{1,2} or \var{4}, or \var{NORMAL} or
  629. \var{DEFAULT}.
  630. As an alternative form one can use \var{\{\$Z1\}}, \var{\{\$Z2\}}
  631. \var{\{\$Z4\}}. Contrary to Delphi, the default is (\var{\{\$Z4\}}).
  632. So the following code
  633. \begin{verbatim}
  634. {$PACKENUM 1}
  635. Type
  636. Days = (monday, tuesday, wednesday, thursday, friday,
  637. saturday, sunday);
  638. \end{verbatim}
  639. will use 1 byte to store a variable of type \var{Days}, whereas it nomally
  640. would use 4 bytes. The above code is equivalent to
  641. \begin{verbatim}
  642. {$Z1}
  643. Type
  644. Days = (monday, tuesday, wednesday, thursday, friday,
  645. saturday, sunday);
  646. \end{verbatim}
  647. \subsection{\var{\$PACKRECORDS} : Alignment of record elements}
  648. This directive controls the byte alignment of the elements in a record,
  649. object or class type definition.
  650. It is of the following form:
  651. \begin{verbatim}
  652. {$PACKRECORDS n}
  653. \end{verbatim}
  654. Where \var{n} is one of 1, 2, 4, 16, \var{C}, \var{NORMAL} or \var{DEFAULT}.
  655. This means that the elements of a record that have size greater than \var{n}
  656. will be aligned on \var{n} byte boundaries. Elements with size less than or
  657. equal to \var{n} will be aligned to a natural boundary, i.e. to a power of
  658. two that is equal to or larger than the element's size. The type \var{C}
  659. is used to specify alignment as by the GNU CC compiler. It should be used
  660. only when making import units for C routines.
  661. The default alignment (which can be selected with \var{DEFAULT}) is 2,
  662. contrary to Turbo Pascal, where it is 1.
  663. More information on this and an example program can be found in the reference
  664. guide, in the section about record types.
  665. \subsection{\var{\$Q} \var{\$OVERFLOWCHECKS}: Overflow checking}
  666. The \var{\{\$Q+\}} or \var{\{\$OVERFLOWCHECKS ON\}} directive turns on
  667. integer overflow checking. This means that the compiler inserts code
  668. to check for overflow when doing computations with integers.
  669. When an overflow occurs, the run-time library will print a message
  670. \var{Overflow at xxx}, and exit the program with exit code 215.
  671. \begin{remark}Overflow checking behaviour is not the same as in
  672. Turbo Pascal since all arithmetic operations are done via 32-bit or
  673. 64-bit values. Furthermore, the \var{Inc()} and \var{Dec} standard system
  674. procedures {\em are} checked for overflow in \fpc, while in Turbo
  675. Pascal they are not.
  676. \end{remark}
  677. Using the \var{\{\$Q-\}} switch switches off the overflow checking code
  678. generation.
  679. The generation of overflow checking code can also be controlled
  680. using the \var{-Co} command line compiler option (see \userref).
  681. \subsection{\var{\$R} or \var{\$RANGECHECKS} : Range checking}
  682. By default, the compiler doesn't generate code to check the ranges of array
  683. indices, enumeration types, subrange types, etc. Specifying the
  684. \var{\{\$R+\}} switch tells the computer to generate code to check these
  685. indices. If, at run-time, an index or enumeration type is specified that is
  686. out of the declared range of the compiler, then a run-time error is
  687. generated, and the program exits with exit code 201. This can happen when
  688. doing a typecast (implicit or explicit) on an enumeration type or subrange
  689. type.
  690. The \var{\{\$RANGECHECKS OFF\}} switch tells the compiler not to generate range checking
  691. code. This may result in faulty program behaviour, but no run-time errors
  692. will be generated.
  693. \begin{remark}The standard functions \var{val} and \var{Read} will also check ranges
  694. when the call is compiled in \var{\{\$R+\}} mode.
  695. \end{remark}
  696. \subsection{\var{\$SATURATION} : Saturation operations (Intel 80x86 only)}
  697. This works only on the intel compiler, and MMX support must be on
  698. (\var{\{\$MMX +\}}) for this to have any effect. See the section on
  699. saturation support (\sees{SaturationSupport}) for more information
  700. on the effect of this directive.
  701. \subsection{\var{\$SMARTLINK} : Use smartlinking}
  702. A unit that is compiled in the \var{\{\$SMARTLINK ON\}} state will be
  703. compiled in such a way that it can be used for smartlinking. This means that
  704. the unit is chopped in logical pieces: each procedure is put in it's own
  705. object file, and all object files are put together in a big archive. When
  706. using such a unit, only the pieces of code that you really need or call,
  707. will be linked in your program, thus reducing the size of your executable
  708. substantially.
  709. Beware: using smartlinked units slows down the compilation process, because
  710. a separate object file must be created for each procedure. If you have units
  711. with many functions and procedures, this can be a time consuming process,
  712. even more so if you use an external assembler (the assembler is called to
  713. assemble each procedure or function code block separately).
  714. The smartlinking directive should be specified {\em before} the unit
  715. declaration part:
  716. \begin{verbatim}
  717. {$SMARTLINK ON}
  718. Unit MyUnit;
  719. Interface
  720. ...
  721. \end{verbatim}
  722. This directive is equivalent to the \var{-Cx} command-line switch.
  723. \subsection{\var{\$STATIC} : Allow use of \var{Static} keyword.}
  724. If you specify the \var{\{\$STATIC ON\}} directive, then \var{Static}
  725. methods are allowed for objects. \var{Static} objects methods do not require
  726. a \var{Self} variable. They are equivalent to \var{Class} methods for
  727. classes. By default, \var{Static} methods are not allowed. Class methods
  728. are always allowed.
  729. By default, the address operator returns an untyped pointer.
  730. This directive is equivalent to the \var{-St} command-line option.
  731. \subsection{\var{\$STOP} : Generate fatal error message}
  732. The following code
  733. \begin{verbatim}
  734. {$STOP This code is erroneous !}
  735. \end{verbatim}
  736. will display an error message when the compiler encounters it.
  737. The compiler will immediatly stop the compilation process.
  738. It has the same effect as the \var{\{\$FATAL\}} directive.
  739. \subsection{\var{\$T} or \var{\$TYPEDADDRESS} : Typed address operator (@)}
  740. In the \var{\{\$T+\}} or \var{\{\$TYPEDADDRESS ON\}} state the @ operator,
  741. when applied to a variable, returns a result of type \var{\^{}T}, if the
  742. type of the variable is \var{T}. In the \var{\{\$T-\}} state, the result is
  743. always an untyped pointer, which is assignment compatible with all other
  744. pointer types.
  745. \subsection{\var{\$UNDEF} : Undefine a symbol}
  746. The directive
  747. \begin{verbatim}
  748. {$UNDEF name}
  749. \end{verbatim}
  750. un-defines the symbol \var{name} if it was previously defined.
  751. \var{Name} is case insensitive.
  752. \subsection{\var{\$V} or \var{\$VARSTRINGCHECKS} : Var-string checking}
  753. When in the \var{+} or \var{ON} state, the compiler checks that strings
  754. passed as parameters are of the same, identical, string type as the declared
  755. parameters of the procedure.
  756. \subsection{\var{\$WAIT} : Wait for enter key press}
  757. If the compiler encounters a
  758. \begin{verbatim}
  759. {$WAIT}
  760. \end{verbatim}
  761. directive, it will resume compiling only after the user has pressed the
  762. enter key. If the generation of info messages is turned on, then the compiler
  763. will display the following message:
  764. \begin{verbatim}
  765. Press <return> to continue
  766. \end{verbatim}
  767. before waiting for a keypress.
  768. \begin{remark}This may interfere with automatic
  769. compilation processes. It should be used for debugging purposes only.
  770. \end{remark}
  771. \subsection{\var{\$WARNING} : Generate warning message}
  772. If the generation of warnings is turned on, through the \var{-vw}
  773. command-line option or the \var{\{\$WARNINGS ON\}} directive, then
  774. \begin{verbatim}
  775. {$WARNING This is dubious code}
  776. \end{verbatim}
  777. will display a warning message when the compiler encounters it.
  778. \subsection{\var{\$WARNINGS} : Emit warnings}
  779. \var{\{\$WARNINGS ON\}} switches the generation of warnings on.
  780. \var{\{\$WARNINGS OFF\}} switches the generation of warnings off.
  781. Contrary to the command-line option \var{-vw} this
  782. is a local switch, this is useful for checking parts of your code.
  783. By default, no warnings are emitted.
  784. \subsection{\var{\$X} or \var{\$EXTENDEDSYNTAX} : Extended syntax}
  785. Extended syntax allows you to drop the result of a function. This means that
  786. you can use a function call as if it were a procedure. Standard this feature
  787. is on. You can switch it off using the \var{\{\$X-\}} or
  788. \var{\{\$EXTENDEDSYNTAX OFF\}}directive.
  789. The following, for instance, will not compile:
  790. \begin{verbatim}
  791. function Func (var Arg : sometype) : longint;
  792. begin
  793. ... { declaration of Func }
  794. end;
  795. ...
  796. {$X-}
  797. Func (A);
  798. \end{verbatim}
  799. The reason this construct is supported is that you may wish to call a
  800. function for certain side-effects it has, but you don't need the function
  801. result. In this case you don't need to assign the function result, saving
  802. you an extra variable.
  803. The command-line compiler switch \var{-Sa1} has the same effect as the
  804. \var{\{\$X+\}} directive.
  805. By default, extended syntax is assumed.
  806. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  807. % Global switches
  808. \section{Global directives}
  809. \label{se:GlobalSwitch}
  810. Global directives affect the whole of the compilation process. That is why
  811. they also have a command-line counterpart. The command-line counterpart is
  812. given for each of the directives.
  813. \subsection{\var{\$APPTYPE} : Specify type of application (Win32 and AmigaOS only)}
  814. The \var{\{\$APPTYPE XXX\}} accepts one argument that can have two possible
  815. values: \var{GUI} or \var{CONSOLE}. It is used to tell the \windows
  816. Operating system if an application is a console application or a graphical
  817. application. By default, a program compiled by \fpc is a console
  818. application. Running it will display a console window. Specifying the
  819. \var{\{\$APPTYPE GUI\}} directive will mark the application as a graphical
  820. application; no console window will be opened when the application is run.
  821. If run from the command-line, the command prompt will be returned immediatly
  822. after the application was started.
  823. Care should be taken when compiling \var{GUI} applications; the \var{Input}
  824. and \var{Output} files are not available in a GUI application, and
  825. attempting to read from or write to them will result in a run-time error.
  826. It is possible to determine the application type of a \windows or \amiga application
  827. at runtime. The \var{IsConsole} constant, declared in the Win32 and Amiga
  828. system units as
  829. \begin{verbatim}
  830. Const
  831. IsConsole : Boolean
  832. \end{verbatim}
  833. contains \var{True} if the application is a console application, \var{False}
  834. if the application is a GUI application.
  835. \subsection{\var{\$D} or \var{\$DEBUGINFO} : Debugging symbols}
  836. When this switch is on,
  837. the compiler inserts GNU debugging information in
  838. the executable. The effect of this switch is the same as the command-line
  839. switch \var{-g}.
  840. By default, insertion of debugging information is off.
  841. \subsection{\var{\$DESCRIPTION} : Application description}
  842. This switch is recognised for compatibility only, but is ignored completely
  843. by the compiler. At a later stage, this switch may be activated.
  844. \subsection{\var{\$E} : Emulation of coprocessor}
  845. This directive controls the emulation of the coprocessor. There is no
  846. command-line counterpart for this directive.
  847. \subsubsection{Intel 80x86 version}
  848. When this switch is enabled, all floating point instructions
  849. which are not supported by standard coprocessor emulators will give out
  850. a warning.
  851. The compiler itself doesn't do the emulation of the coprocessor.
  852. To use coprocessor emulation under \dos go32v2 you must use the
  853. emu387 unit, which contains correct initialization code for the
  854. emulator.
  855. Under \linux and most \unix'es, the kernel takes care of the
  856. coprocessor support.
  857. \subsubsection{Motorola 680x0 version}
  858. When the switch is on, no floating point opcodes are emitted
  859. by the code generator. Instead, internal run-time library routines
  860. are called to do the necessary calculations. In this case all
  861. real types are mapped to the single IEEE floating point type.
  862. \begin{remark}By default, emulation is on. It is possible to
  863. intermix emulation code with real floating point opcodes, as
  864. long as the only type used is single or real.
  865. \end{remark}
  866. Under \linux and most \unix'es, the kernel takes care of the
  867. coprocessor support.
  868. \subsection{\var{\$G} : Generate 80286 code}
  869. This option is recognised for Turbo Pascal compatibility, but is ignored,
  870. since the compiler works only on 32-bit and 64-bit processors.
  871. \subsection{\var{\$INCLUDEPATH} : Specify include path.}
  872. This option serves to specify the include path, where the compiler looks for
  873. include files. \var{\{\$INCLUDEPATH XXX\}} will add \var{XXX} to the include
  874. path. \var{XXX} can contain one or more paths, separated by semi-colons or
  875. colons.
  876. For example:
  877. \begin{verbatim}
  878. {$INCLUDEPATH ../inc;../i386}
  879. {$I strings.inc}
  880. \end{verbatim}
  881. will add the directories \file{../inc} and \file{../i386} to the include
  882. path of the compiler. The compiler will look for the file \file{strings.inc}
  883. in both these directories, and will include the first found file. This directive is
  884. equivalent to the \var{-Fi} command-line switch.
  885. Caution is in order when using this directive: If you distribute files, the
  886. places of the files may not be the same as on your machine; moreover, the
  887. directory structure may be different. In general it would be fair to say
  888. that you should avoid using {\em absolute} paths, instead use {\em relative}
  889. paths, as in the example above. Only use this directive if you are certain
  890. of the places where the files reside. If you are not sure, it is better
  891. practice to use makefiles and makefile variables.
  892. \subsection{\var{\$L} or \var{\$LOCALSYMBOLS} : Local symbol information}
  893. This switch (not to be confused with the \var{\{\$L file\}} file linking
  894. directive) is recognised for Turbo Pascal compatibility, but is ignored.
  895. Generation of symbol information is controlled by the \var{\$D} switch.
  896. \subsection{\var{\$LIBRARYPATH} : Specify library path.}
  897. This option serves to specify the library path, where the linker looks for
  898. static or dynamic libraries. \var{\{\$LIBRARYPATH XXX\}} will add \var{XXX}
  899. to the library path. \var{XXX} can contain one or more paths, separated
  900. by semi-colons or colons.
  901. For example:
  902. \begin{verbatim}
  903. {$LIBRARYPATH /usr/X11/lib;/usr/local/lib}
  904. {$LINKLIB X11}
  905. \end{verbatim}
  906. will add the directories \file{/usr/X11/lib} and \file{/usr/local/lib} to
  907. the linker library path. The linker will look for the library \file{libX11.so}
  908. in both these directories, and use the first found file. This directive is
  909. equivalent to the \var{-Fl} command-line switch.
  910. Caution is in order when using this directive: If you distribute files, the
  911. places of the libraries may not be the same as on your machine; moreover, the
  912. directory structure may be different. In general it would be fair to say
  913. that you should avoid using this directive. If you are not sure, it is better
  914. practice to use makefiles and makefile variables.
  915. \subsection{\var{\$M} or \var{\$MEMORY} : Memory sizes}
  916. This switch can be used to set the heap and stacksize. It's format is as
  917. follows:
  918. \begin{verbatim}
  919. {$M StackSize,HeapSize}
  920. \end{verbatim}
  921. where \var{StackSize} and \var{HeapSize} should be two integer values,
  922. greater than 1024. The first number sets the size of the stack, and the
  923. second the size of the heap. (Stack setting is ignored under \linux, \netbsd and \freebsd).
  924. The two numbers can be set on the command line using the \var{-Ch}
  925. and \var{-Cs} switches.
  926. \subsection{\var{\$MODE} : Set compiler compatibility mode}
  927. The \var{\{\$MODE\}} sets the compatibility mode of the compiler. This
  928. is equivalent to setting one of the command-line options \var{-So},
  929. \var{-Sd}, \var{-Sp} or \var{-S2}. it has the following arguments:
  930. \begin{description}
  931. \item[Default] Default mode. This reverts back to the mode that was set on
  932. the command-line.
  933. \item[Delphi] Delphi compatibility mode. All object-pascal extensions are
  934. enabled. This is the same as the command-line option \var{-Sd}.
  935. \item[TP] Turbo pascal compatibility mode. Object pascal extensions are
  936. disabled, except ansistrings, which remain valid.
  937. This is the same as the command-line option \var{-So}.
  938. \item[FPC] FPC mode. This is the default, if no command-line switch is
  939. supplied.
  940. \item[OBJFPC] Object pascal mode. This is the same as the \var{-S2}
  941. command-line option.
  942. \item[GPC] GNU pascal mode. This is the same as the \var{-Sp} command-line
  943. option.
  944. \end{description}
  945. For an exact description of each of these modes, see appendix \ref{ch:AppD},
  946. on page \pageref{ch:AppD}.
  947. \subsection{\var{\$N} : Numeric processing }
  948. This switch is recognised for Turbo Pascal compatibility, but is otherwise
  949. ignored, since the compiler always uses the coprocessor for floating point
  950. mathematics.
  951. \subsection{\var{\$O} : Overlay code generation }
  952. This switch is recognised for Turbo Pascal compatibility, but is otherwise
  953. ignored.
  954. \subsection{\var{\$OBJECTPATH} : Specify object path.}
  955. This option serves to specify the object path, where the compiler looks for
  956. object files. \var{\{\$OBJECTPATH XXX\}} will add \var{XXX} to the object
  957. path. \var{XXX} can contain one or more paths, separated by semi-colons or
  958. colons.
  959. For example:
  960. \begin{verbatim}
  961. {$OBJECTPATH ../inc;../i386}
  962. {$L strings.o}
  963. \end{verbatim}
  964. will add the directories \file{../inc} and \file{../i386} to the
  965. object path of the compiler. The compiler will look for the file \file{strings.o}
  966. in both these directories, and will link the first found file in the
  967. program. This directive is equivalent to the \var{-Fo} command-line switch.
  968. Caution is in order when using this directive: If you distribute files, the
  969. places of the files may not be the same as on your machine; moreover, the
  970. directory structure may be different. In general it would be fair to say
  971. that you should avoid using {\em absolute} paths, instead use {\em relative}
  972. paths, as in the example above. Only use this directive if you are certain
  973. of the places where the files reside. If you are not sure, it is better
  974. practice to use makefiles and makefile variables.
  975. \subsection{\var{\$S} : Stack checking}
  976. The \var{\{\$S+\}} directive tells the compiler to generate stack checking
  977. code. This generates code to check if a stack overflow occurred, i.e. to see
  978. whether the stack has grown beyond its maximally allowed size. If the stack
  979. grows beyond the maximum size, then a run-time error is generated, and the
  980. program will exit with exit code 202.
  981. Specifying \var{\{\$S-\}} will turn generation of stack-checking code off.
  982. The command-line compiler switch \var{-Ct} has the same effect as the
  983. \var{\{\$S+\}} directive.
  984. By default, no stack checking is performed.
  985. \subsection{\var{\$UNITPATH} : Specify unit path.}
  986. This option serves to specify the unit path, where the compiler looks for
  987. unit files. \var{\{\$UNITPATH XXX\}} will add \var{XXX} to the unit
  988. path. \var{XXX} can contain one or more paths, separated by semi-colons or
  989. colons.
  990. For example:
  991. \begin{verbatim}
  992. {$UNITPATH ../units;../i386/units}
  993. Uses strings;
  994. \end{verbatim}
  995. will add the directories \file{../units} and \file{../i386/units} to the unit
  996. path of the compiler. The compiler will look for the file \file{strings.ppu}
  997. in both these directories, and will link the first found file in the
  998. program. This directive is equivalent to the \var{-Fu} command-line switch.
  999. Caution is in order when using this directive: If you distribute files, the
  1000. places of the files may not be the same as on your machine; moreover, the
  1001. directory structure may be different. In general it would be fair to say
  1002. that you should avoid using {\em absolute} paths, instead use {\em relative}
  1003. paths, as in the example above. Only use this directive if you are certain
  1004. of the places where the files reside. If you are not sure, it is better
  1005. practice to use makefiles and makefile variables.
  1006. \subsection{\var{\$W} or \var{\$STACKFRAMES} : Generate stackframes}
  1007. The \var{\{\$W\}} switch directove controls the generation of stackframes.
  1008. In the on state, the compiler will generate a
  1009. stackframe for every procedure or function.
  1010. In the off state, the compiler will omit the generation of a stackframe if
  1011. the following conditions are satisfied:
  1012. \begin{itemize}
  1013. \item The procedure has no parameters.
  1014. \item The procedure has no local variables.
  1015. \item If the procedure is not an \var{assembler} procedure, it must not have
  1016. a \var{asm \dots end;} block.
  1017. \item it is not a constuctor or desctructor.
  1018. \end{itemize}
  1019. If these conditions are satisfied, the stack frame will be omitted.
  1020. \subsection{\var{\$Y} or \var{\$REFERENCEINFO} : Insert Browser information}
  1021. This switch controls the generation of browser inforation. It is recognized
  1022. for compatibility with Turbo Pascal and Delphi only, as Browser information
  1023. generation is not yet fully supported.
  1024. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1025. % Using conditionals and macros
  1026. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1027. \chapter{Using conditionals, messages and macros}
  1028. \label{ch:CondMessageMacro}
  1029. The \fpc compiler supports conditionals as in normal Turbo Pascal. It does,
  1030. however, more than that. It allows you to make macros which can be used in
  1031. your code, and it allows you to define messages or errors which will be
  1032. displayed when compiling.
  1033. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1034. % Conditionals
  1035. \section{Conditionals}
  1036. \label{se:Conditionals}
  1037. The rules for using conditional symbols are the same as under Turbo Pascal.
  1038. Defining a symbol goes as follows:
  1039. \begin{verbatim}
  1040. {$define Symbol}
  1041. \end{verbatim}
  1042. From this point on in your code, the compiler knows the symbol \var{Symbol}.
  1043. Symbols are, like the Pascal language, case insensitive.
  1044. You can also define a symbol on the command line. the \var{-dSymbol} option
  1045. defines the symbol \var{Symbol}. You can specify as many symbols on the
  1046. command line as you want.
  1047. Undefining an existing symbol is done in a similar way:
  1048. \begin{verbatim}
  1049. {$undef Symbol}
  1050. \end{verbatim}
  1051. If the symbol didn't exist yet, this doesn't do anything. If the symbol
  1052. existed previously, the symbol will be erased, and will not be recognized
  1053. any more in the code following the \verb|{$undef \dots}| statement.
  1054. You can also undefine symbols from the command line with the \var{-u}
  1055. command-line switch.
  1056. To compile code conditionally, depending on whether a symbol is defined or
  1057. not, you can enclose the code in a \verb|{$ifdef Symbol}| \dots \verb|{$endif}|
  1058. pair. For instance the following code will never be compiled:
  1059. \begin{verbatim}
  1060. {$undef MySymbol}
  1061. {$ifdef Mysymbol}
  1062. DoSomething;
  1063. ...
  1064. {$endif}
  1065. \end{verbatim}
  1066. Similarly, you can enclose your code in a \verb|{$ifndef Symbol}| \dots \verb|{$endif}|
  1067. pair. Then the code between the pair will only be compiled when the used
  1068. symbol doesn't exist. For example, in the following example, the call to the
  1069. \var{DoSomething} will always be compiled:
  1070. \begin{verbatim}
  1071. {$undef MySymbol}
  1072. {$ifndef Mysymbol}
  1073. DoSomething;
  1074. ...
  1075. {$endif}
  1076. \end{verbatim}
  1077. You can combine the two alternatives in one structure, namely as follows
  1078. \begin{verbatim}
  1079. {$ifdef Mysymbol}
  1080. DoSomething;
  1081. {$else}
  1082. DoSomethingElse
  1083. {$endif}
  1084. \end{verbatim}
  1085. In this example, if \var{MySymbol} exists, then the call to \var{DoSomething}
  1086. will be compiled. If it doesn't exist, the call to \var{DoSomethingElse} is
  1087. compiled.
  1088. Except for the Turbo Pascal constructs the \fpc compiler also
  1089. supports a stronger conditional compile mechanism: The \var{\{\$if\}}
  1090. construct.
  1091. The prototype of this construct is as follows:
  1092. \begin{verbatim}
  1093. {$if expr}
  1094. CompileTheseLines;
  1095. {$else}
  1096. BetterCompileTheseLines;
  1097. {$endif}
  1098. \end{verbatim}
  1099. In this directive \var{expr} is a Pascal expression which is evaluated using
  1100. strings, unless both parts of a comparision can be evaluated as numbers,
  1101. in which case they are evaluated using numbers\footnote{Otherwise
  1102. \var{\{\$if 8>54\}} would evaluate to \var{True}}.
  1103. If the complete expression evaluates to \var{'0'}, then it is considered
  1104. false and rejected. Otherwise it is considered true and accepted. This may
  1105. have unexpected consequences:
  1106. \begin{verbatim}
  1107. {$if 0}
  1108. \end{verbatim}
  1109. will evaluate to \var{False} and be rejected, while
  1110. \begin{verbatim}
  1111. {$if 00}
  1112. \end{verbatim}
  1113. will evaluate to \var{True}.
  1114. You can use any Pascal operator to construct your expression: \var{=, <>,
  1115. >, <, >=, <=, AND, NOT, OR} and you can use round brackets to change the
  1116. precedence of the operators.
  1117. The following example shows you many of the possibilities:
  1118. \begin{verbatim}
  1119. {$ifdef fpc}
  1120. var
  1121. y : longint;
  1122. {$else fpc}
  1123. var
  1124. z : longint;
  1125. {$endif fpc}
  1126. var
  1127. x : longint;
  1128. begin
  1129. {$if (fpc_version=0) and (fpc_release>6) and (fpc_patch>4)}
  1130. {$info At least this is version 0.9.5}
  1131. {$else}
  1132. {$fatal Problem with version check}
  1133. {$endif}
  1134. {$define x:=1234}
  1135. {$if x=1234}
  1136. {$info x=1234}
  1137. {$else}
  1138. {$fatal x should be 1234}
  1139. {$endif}
  1140. {$if 12asdf and 12asdf}
  1141. {$info $if 12asdf and 12asdf is ok}
  1142. {$else}
  1143. {$fatal $if 12asdf and 12asdf rejected}
  1144. {$endif}
  1145. {$if 0 or 1}
  1146. {$info $if 0 or 1 is ok}
  1147. {$else}
  1148. {$fatal $if 0 or 1 rejected}
  1149. {$endif}
  1150. {$if 0}
  1151. {$fatal $if 0 accepted}
  1152. {$else}
  1153. {$info $if 0 is ok}
  1154. {$endif}
  1155. {$if 12=12}
  1156. {$info $if 12=12 is ok}
  1157. {$else}
  1158. {$fatal $if 12=12 rejected}
  1159. {$endif}
  1160. {$if 12<>312}
  1161. {$info $if 12<>312 is ok}
  1162. {$else}
  1163. {$fatal $if 12<>312 rejected}
  1164. {$endif}
  1165. {$if 12<=312}
  1166. {$info $if 12<=312 is ok}
  1167. {$else}
  1168. {$fatal $if 12<=312 rejected}
  1169. {$endif}
  1170. {$if 12<312}
  1171. {$info $if 12<312 is ok}
  1172. {$else}
  1173. {$fatal $if 12<312 rejected}
  1174. {$endif}
  1175. {$if a12=a12}
  1176. {$info $if a12=a12 is ok}
  1177. {$else}
  1178. {$fatal $if a12=a12 rejected}
  1179. {$endif}
  1180. {$if a12<=z312}
  1181. {$info $if a12<=z312 is ok}
  1182. {$else}
  1183. {$fatal $if a12<=z312 rejected}
  1184. {$endif}
  1185. {$if a12<z312}
  1186. {$info $if a12<z312 is ok}
  1187. {$else}
  1188. {$fatal $if a12<z312 rejected}
  1189. {$endif}
  1190. {$if not(0)}
  1191. {$info $if not(0) is OK}
  1192. {$else}
  1193. {$fatal $if not(0) rejected}
  1194. {$endif}
  1195. {$info *************************************************}
  1196. {$info * Now have to follow at least 2 error messages: *}
  1197. {$info *************************************************}
  1198. {$if not(0}
  1199. {$endif}
  1200. {$if not(<}
  1201. {$endif}
  1202. end.
  1203. \end{verbatim}
  1204. As you can see from the example, this construct isn't useful when used
  1205. with normal symbols, only if you use macros, which are explained in
  1206. \sees{Macros}. They can be very useful. When trying this example, you must
  1207. switch on macro support, with the \var{-Sm} command-line switch.
  1208. \subsection{Predefined symbols}
  1209. The \fpc compiler defines some symbols before starting to compile your
  1210. program or unit. You can use these symbols to differentiate between
  1211. different versions of the compiler, and between different compilers.
  1212. To get all the possible defines when starting compilation,
  1213. see appendix \ref{ch:AppG}
  1214. \begin{remark}Symbols, even when they're defined in the interface part of
  1215. a unit, are not available outside that unit.
  1216. \end{remark}
  1217. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1218. % Macros
  1219. \section{Messages}
  1220. \label{se:Messages}
  1221. \fpc lets you define normal, warning and error messages in your code.
  1222. Messages can be used to display useful information, such as copyright
  1223. notices, a list of symbols that your code reacts on etc.
  1224. Warnings can be used if you think some part of your code is still buggy, or
  1225. if you think that a certain combination of symbols isn't useful.
  1226. Error messages can be useful if you need a certain symbol to be defined,
  1227. to warn that a certain variable isn't defined, or when the compiler
  1228. version isn't suitable for your code.
  1229. The compiler treats these messages as if they were generated by the
  1230. compiler. This means that if you haven't turned on warning messages, the
  1231. warning will not be displayed. Errors are always displayed, and the
  1232. compiler stops if 50 errors have occurred. After a fatal error, the compiler
  1233. stops at once.
  1234. For messages, the syntax is as follows:
  1235. \begin{verbatim}
  1236. {$Message Message text}
  1237. \end{verbatim}
  1238. or
  1239. \begin{verbatim}
  1240. {$Info Message text}
  1241. \end{verbatim}
  1242. For notes:
  1243. \begin{verbatim}
  1244. {$Note Message text}
  1245. \end{verbatim}
  1246. For warnings:
  1247. \begin{verbatim}
  1248. {$Warning Warning Message text}
  1249. \end{verbatim}
  1250. For errors:
  1251. \begin{verbatim}
  1252. {$Error Error Message text}
  1253. \end{verbatim}
  1254. Lastly, for fatal errors:
  1255. \begin{verbatim}
  1256. {$Fatal Error Message text}
  1257. \end{verbatim}
  1258. or
  1259. \begin{verbatim}
  1260. {$Stop Error Message text}
  1261. \end{verbatim}
  1262. The difference between \var{\$Error} and \var{\$FatalError} or \var{\$Stop}
  1263. messages is that when the compiler encounters an error, it still continues
  1264. to compile. With a fatal error, the compiler stops.
  1265. \begin{remark}You cannot use the '\var{\}}' character in your message, since
  1266. this will be treated as the closing brace of the message.
  1267. \end{remark}
  1268. As an example, the following piece of code will generate an error when
  1269. the symbol \var{RequiredVar} isn't defined:
  1270. \begin{verbatim}
  1271. {$ifndef RequiredVar}
  1272. {$Error Requiredvar isn't defined !}
  1273. {$endif}
  1274. \end{verbatim}
  1275. But the compiler will continue to compile. It will not, however, generate a
  1276. unit file or a program (since an error occurred).
  1277. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1278. % Macros
  1279. \section{Macros}
  1280. \label{se:Macros}
  1281. Macros are very much like symbols in their syntax, the difference is that
  1282. macros have a value whereas a symbol simply is defined or is not defined.
  1283. If you want macro support, you need to specify the \var{-Sm} command-line
  1284. switch, otherwise your macro will be regarded as a symbol.
  1285. Defining a macro in your program is done in the same way as defining a symbol;
  1286. in a \var{\{\$define\}} preprocessor statement\footnote{In compiler
  1287. versions older than 0.9.8, the assignment operator for a macros wasn't
  1288. \var{:=} but \var{=}}:
  1289. \begin{verbatim}
  1290. {$define ident:=expr}
  1291. \end{verbatim}
  1292. If the compiler encounters \var{ident} in the rest of the source file, it
  1293. will be replaced immediately by \var{expr}. This replacement works
  1294. recursive, meaning that when the compiler expanded one of your macros, it
  1295. will look at the resulting expression again to see if another replacement
  1296. can be made. You need to be careful with this, because an infinite loop can
  1297. occur in this manner.
  1298. Here are two examples which illustrate the use of macros:
  1299. \begin{verbatim}
  1300. {$define sum:=a:=a+b;}
  1301. ...
  1302. sum { will be expanded to 'a:=a+b;'
  1303. remark the absence of the semicolon}
  1304. ...
  1305. {$define b:=100}
  1306. sum { Will be expanded recursively to a:=a+100; }
  1307. ...
  1308. \end{verbatim}
  1309. The previous example could go wrong:
  1310. \begin{verbatim}
  1311. {$define sum:=a:=a+b;}
  1312. ...
  1313. sum { will be expanded to 'a:=a+b;'
  1314. remark the absence of the semicolon}
  1315. ...
  1316. {$define b=sum} { DON'T do this !!!}
  1317. sum { Will be infinitely recursively expanded \dots }
  1318. ...
  1319. \end{verbatim}
  1320. On my system, the last example results in a heap error, causing the compiler
  1321. to exit with a run-time error 203.
  1322. \begin{remark}Macros defined in the interface part of a unit are not
  1323. available outside that unit! They can just be used as a notational
  1324. convenience, or in conditional compiles.
  1325. \end{remark}
  1326. By default the compiler predefines three
  1327. macros, containing the version number, the release number and the patch
  1328. number. They are listed in \seet{DefMacros}.
  1329. \begin{FPCltable}{ll}{Predefined macros}{DefMacros} \hline
  1330. Symbol & Contains \\ \hline
  1331. \var{FPC\_VERSION} & The version number of the compiler. \\
  1332. \var{FPC\_RELEASE} & The release number of the compiler. \\
  1333. \var{FPC\_PATCH} & The patch number of the compiler. \\
  1334. \hline
  1335. \end{FPCltable}
  1336. \begin{remark}Don't forget that macros support isn't on by default. You
  1337. need to compile with the \var{-Sm} command-line switch.
  1338. \end{remark}
  1339. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1340. % Using assembly language
  1341. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1342. \chapter{Using Assembly language}
  1343. \label{ch:AsmLang}
  1344. \fpc supports inserting assembler statements in your code. The
  1345. mechanism for this is the same as under Turbo Pascal. There are, however
  1346. some substantial differences, as will be explained in the following
  1347. sections.
  1348. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1349. % 80x86 Assembler syntax
  1350. \section{Intel 80x86 Inline assembler}
  1351. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1352. % Intel syntax
  1353. \subsection{Intel syntax}
  1354. \label{se:Intel}
  1355. \fpc supports Intel syntax for the Intel family of Ix86 processors
  1356. in it's \var{asm} blocks.
  1357. The Intel syntax in your \var{asm} block is converted to AT\&T syntax by the
  1358. compiler, after which it is inserted in the compiled source.
  1359. The supported assembler constructs are a subset of the normal assembly
  1360. syntax. In what follows we specify what constructs are not supported in
  1361. \fpc, but which exist in Turbo Pascal:
  1362. \begin{itemize}
  1363. \item The \var{TBYTE} qualifier is not supported.
  1364. \item The \var{\&} identifier override is not supported.
  1365. \item The \var{HIGH} operator is not supported.
  1366. \item The \var{LOW} operator is not supported.
  1367. \item The \var{OFFSET} and \var{SEG} operators are not supported.
  1368. Use \var{LEA} and the various \var{Lxx} instructions instead.
  1369. \item Expressions with constant strings are not allowed.
  1370. \item Access to record fields via parenthesis is not allowed
  1371. \item Typecasts with normal pascal types are not allowed, only
  1372. recognized assembler typecasts are allowed. Example:
  1373. \begin{verbatim}
  1374. mov al, byte ptr MyWord -- allowed,
  1375. mov al, byte(MyWord) -- allowed,
  1376. mov al, shortint(MyWord) -- not allowed.
  1377. \end{verbatim}
  1378. \item Pascal type typecasts on constants are not allowed.
  1379. Example:
  1380. \begin{verbatim}
  1381. const s= 10; const t = 32767;
  1382. \end{verbatim}
  1383. in Turbo Pascal:
  1384. \begin{verbatim}
  1385. mov al, byte(s) -- useless typecast.
  1386. mov al, byte(t) -- syntax error!
  1387. \end{verbatim}
  1388. In this parser, either of those cases will give out a syntax error.
  1389. \item Constant references expressions with constants only are not
  1390. allowed (in all cases they do not work in protected mode,
  1391. under \linux i386). Examples:
  1392. \begin{verbatim}
  1393. mov al,byte ptr ['c'] -- not allowed.
  1394. mov al,byte ptr [100h] -- not allowed.
  1395. \end{verbatim}
  1396. (This is due to the limitation of Turbo Assembler).
  1397. \item Brackets within brackets are not allowed
  1398. \item Expressions with segment overrides fully in brackets are
  1399. presently not supported, but they can easily be implemented
  1400. in BuildReference if requested. Example:
  1401. \begin{verbatim}
  1402. mov al,[ds:bx] -- not allowed
  1403. \end{verbatim}
  1404. use instead:
  1405. \begin{verbatim}
  1406. mov al,ds:[bx]
  1407. \end{verbatim}
  1408. \item Possible allowed indexing are as follows:
  1409. \begin{itemize}
  1410. \item \var{Sreg:[REG+REG*SCALING+/-disp]}
  1411. \item \var{SReg:[REG+/-disp]}
  1412. \item \var{SReg:[REG]}
  1413. \item \var{SReg:[REG+REG+/-disp]}
  1414. \item \var{SReg:[REG+REG*SCALING]}
  1415. \end{itemize}
  1416. Where \var{Sreg} is optional and specifies the segment override.
  1417. {\em Notes:}
  1418. \begin{enumerate}
  1419. \item The order of terms is important contrary to Turbo Pascal.
  1420. \item The Scaling value must be a value, and not an identifier
  1421. to a symbol. Examples:
  1422. \begin{verbatim}
  1423. const myscale = 1;
  1424. ...
  1425. mov al,byte ptr [esi+ebx*myscale] -- not allowed.
  1426. \end{verbatim}
  1427. use:
  1428. \begin{verbatim}
  1429. mov al, byte ptr [esi+ebx*1]
  1430. \end{verbatim}
  1431. \end{enumerate}
  1432. \item Possible variable identifier syntax is as follows:
  1433. (Id = Variable or typed constant identifier.)
  1434. \begin{enumerate}
  1435. \item \var{ID}
  1436. \item \var{[ID]}
  1437. \item \var{[ID+expr]}
  1438. \item \var{ID[expr]}
  1439. \end{enumerate}
  1440. Possible fields are as follow:
  1441. \begin{enumerate}
  1442. \item \var{ID.subfield.subfield \dots}
  1443. \item \var{[ref].ID.subfield.subfield \dots}
  1444. \item \var{[ref].typename.subfield \dots}
  1445. \end{enumerate}
  1446. \item Local abels: Contrary to Turbo Pascal, local labels, must
  1447. at least contain one character after the local symbol indicator.
  1448. Example:
  1449. \begin{verbatim}
  1450. @: -- not allowed
  1451. \end{verbatim}
  1452. use instead, for example:
  1453. \begin{verbatim}
  1454. @1: -- allowed
  1455. \end{verbatim}
  1456. \item Contrary to Turbo Pascal local references cannot be used as references,
  1457. only as displacements. Example:
  1458. \begin{verbatim}
  1459. lds si,@mylabel -- not allowed
  1460. \end{verbatim}
  1461. \item Contrary to Turbo Pascal, \var{SEGCS}, \var{SEGDS}, \var{SEGES} and
  1462. \var{SEGSS} segment overrides are presently not supported.
  1463. (This is a planned addition though).
  1464. \item Contrary to Turbo Pascal where memory sizes specifiers can
  1465. be practically anywhere, the \fpc Intel inline assembler requires
  1466. memory size specifiers to be outside the brackets. Example:
  1467. \begin{verbatim}
  1468. mov al,[byte ptr myvar] -- not allowed.
  1469. \end{verbatim}
  1470. use:
  1471. \begin{verbatim}
  1472. mov al,byte ptr [myvar] -- allowed.
  1473. \end{verbatim}
  1474. \item Base and Index registers must be 32-bit registers.
  1475. (limitation of the GNU Assembler).
  1476. \item \var{XLAT} is equivalent to \var{XLATB}.
  1477. \item Only Single and Double FPU opcodes are supported.
  1478. \item Floating point opcodes are currently not supported
  1479. (except those which involve only floating point registers).
  1480. \end{itemize}
  1481. The Intel inline assembler supports the following macros:
  1482. \begin{description}
  1483. \item [@Result] represents the function result return value.
  1484. \item [Self] represents the object method pointer in methods.
  1485. \end{description}
  1486. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1487. % AT&T syntax
  1488. \subsection{AT\&T Syntax}
  1489. \label{se:AttSyntax}
  1490. \fpc uses the \gnu \var{as} assembler to generate its object files for
  1491. the Intel Ix86 processors. Since
  1492. the \gnu assembler uses AT\&T assembly syntax, the code you write should
  1493. use the same syntax. The differences between AT\&T and Intel syntax as used
  1494. in Turbo Pascal are summarized in the following:
  1495. \begin{itemize}
  1496. \item The opcode names include the size of the operand. In general, one can
  1497. say that the AT\&T opcode name is the Intel opcode name, suffixed with a
  1498. '\var{l}', '\var{w}' or '\var{b}' for, respectively, longint (32 bit),
  1499. word (16 bit) and byte (8 bit) memory or register references. As an example,
  1500. the Intel construct \mbox{'\var{mov al bl}} is equivalent to the AT\&T style '\var{movb
  1501. \%bl,\%al}' instruction.
  1502. \item AT\&T immediate operands are designated with '\$', while Intel syntax
  1503. doesn't use a prefix for immediate operands. Thus the Intel construct
  1504. '\var{mov ax, 2}' becomes '\var{movb \$2, \%al}' in AT\&T syntax.
  1505. \item AT\&T register names are preceded by a '\var{\%}' sign.
  1506. They are undelimited in Intel syntax.
  1507. \item AT\&T indicates absolute jump/call operands with '\var{*}', Intel
  1508. syntax doesn't delimit these addresses.
  1509. \item The order of the source and destination operands are switched. AT\&T
  1510. syntax uses '\var{Source, Dest}', while Intel syntax features '\var{Dest,
  1511. Source}'. Thus the Intel construct '\var{add eax, 4}' transforms to
  1512. '\var{addl \$4, \%eax}' in the AT\&T dialect.
  1513. \item Immediate long jumps are prefixed with the '\var{l}' prefix. Thus the
  1514. Intel '\var{call/jmp section:offset'} is transformed to '\var{lcall/ljmp
  1515. \$section,\$offset}'. Similarly the far return is '\var{lret}', instead of the
  1516. Intel '\var{ret far}'.
  1517. \item Memory references are specified differently in AT\&T and Intel
  1518. assembly. The Intel indirect memory reference
  1519. \begin{quote}
  1520. \var{Section:[Base + Index*Scale + Offs]}
  1521. \end{quote}
  1522. is written in AT\&T syntax as:
  1523. \begin{quote}
  1524. \var{Section:Offs(Base,Index,Scale)}
  1525. \end{quote}
  1526. Where \var{Base} and \var{Index} are optional 32-bit base and index
  1527. registers, and \var{Scale} is used to multiply \var{Index}. It can take the
  1528. values 1,2,4 and 8. The \var{Section} is used to specify an optional section
  1529. register for the memory operand.
  1530. \end{itemize}
  1531. More information about the AT\&T syntax can be found in the \var{as} manual,
  1532. although the following differences with normal AT\&T assembly must be taken
  1533. into account:
  1534. \begin{itemize}
  1535. \item Only the following directives are presently supported:
  1536. \begin{description}
  1537. \item[.byte]
  1538. \item[.word]
  1539. \item[.long]
  1540. \item[.ascii]
  1541. \item[.asciz]
  1542. \item[.globl]
  1543. \end{description}
  1544. \item The following directives are recognized but are not
  1545. supported:
  1546. \begin{description}
  1547. \item[.align]
  1548. \item[.lcomm]
  1549. \end{description}
  1550. Eventually they will be supported.
  1551. \item Directives are case sensitive, other identifiers are not case sensitive.
  1552. \item Contrary to GAS local labels/symbols {\em must} start with \var{.L}
  1553. \item The not operator \var{'!'} is not supported.
  1554. \item String expressions in operands are not supported.
  1555. \item CBTW,CWTL,CWTD and CLTD are not supported, use the normal intel
  1556. equivalents instead.
  1557. \item Constant expressions which represent memory references are not
  1558. allowed even though constant immediate value expressions are supported.
  1559. Examples:
  1560. \begin{verbatim}
  1561. const myid = 10;
  1562. ...
  1563. movl $myid,%eax -- allowed
  1564. movl myid(%esi),%eax -- not allowed.
  1565. \end{verbatim}
  1566. \item When the \var{.globl} directive is found, the symbol following
  1567. it is made public and is immediately emitted.
  1568. Therefore label names with this name will be ignored.
  1569. \item Only Single and Double FPU opcodes are supported.
  1570. \end{itemize}
  1571. The AT\&T inline assembler supports the following macros:
  1572. \begin{description}
  1573. \item [\_\_RESULT] represents the function result return value.
  1574. \item [\_\_SELF] represents the object method pointer in methods.
  1575. \item [\_\_OLDEBP] represents the old base pointer in recusrive routines.
  1576. \end{description}
  1577. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1578. % Motorola 680x0 assembler
  1579. \section{Motorola 680x0 Inline assembler}
  1580. The inline assembler reader for the Motorola 680x0 family of processors,
  1581. uses the Motorola Assembler syntax (q.v). A few differences do exit:
  1582. \begin{itemize}
  1583. \item Local labels start with the @ character, such as
  1584. \begin{verbatim}
  1585. @MyLabel:
  1586. \end{verbatim}
  1587. \item The \var{XDEF} directive in an assembler block will
  1588. make the symbol available publicly with the specified name
  1589. (this name is case sensitive)
  1590. \item The \var{DB}, \var{DW}, \var{DD} directives can only
  1591. be used to declare constants which will be stored in the
  1592. code segment.
  1593. \item The \var{Align} directive is not supported.
  1594. \item Arithmetic operations on constant expression use the same
  1595. operands as the intel version (e.g : \var{AND}, \var{XOR} ...)
  1596. \item Segment directives are not supported
  1597. \item Only 68000 opcodes are currently supported
  1598. \end{itemize}
  1599. The inline assembler supports the following macros:
  1600. \begin{description}
  1601. \item [@Result] represents the function result return value.
  1602. \item [Self] represents the object method pointer in methods.
  1603. \end{description}
  1604. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1605. % Telling the compiler what registers have changed
  1606. \section{Signaling changed registers}
  1607. \label{se:RegChanges}
  1608. When the compiler uses variables, it sometimes stores them, or the result of
  1609. some calculations, in the processor registers. If you insert assembler code
  1610. in your program that modifies the processor registers, then this may
  1611. interfere with the compiler's idea about the registers. To avoid this
  1612. problem, \fpc allows you to tell the compiler which registers have changed.
  1613. The compiler will then avoid using these registers. Telling the compiler
  1614. which registers have changed is done by specifying a set of register names
  1615. behind an assembly block, as follows:
  1616. \begin{verbatim}
  1617. asm
  1618. ...
  1619. end ['R1', ... ,'Rn'];
  1620. \end{verbatim}
  1621. Here \var{R1} to \var{Rn} are the names of the registers you
  1622. modify in your assembly code.
  1623. As an example:
  1624. \begin{verbatim}
  1625. asm
  1626. movl BP,%eax
  1627. movl 4(%eax),%eax
  1628. movl %eax,__RESULT
  1629. end ['EAX'];
  1630. \end{verbatim}
  1631. This example tells the compiler that the \var{EAX} register was modified.
  1632. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1633. % Generated code
  1634. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1635. \chapter{Generated code}
  1636. \label{ch:GenCode}
  1637. The \fpc compiler relies on the assembler to make object files. It generates
  1638. just the assembly language file. In the following two sections, we discuss
  1639. what is generated when you compile a unit or a program.
  1640. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1641. % Units
  1642. \section{Units}
  1643. \label{se:Units}
  1644. When you compile a unit, the \fpc compiler generates 2 files:
  1645. \begin{enumerate}
  1646. \item A unit description file.
  1647. \item An assembly language file.
  1648. \end{enumerate}
  1649. The assembly language file contains the actual source code for the
  1650. statements in your unit, and the necessary memory allocations for any
  1651. variables you use in your unit. This file is converted by the assembler to
  1652. an object file (with extension \file{.o}) which can then be linked to other
  1653. units and your program, to form an executable.
  1654. By default, the assembly file is removed after it has been compiled.
  1655. Only in the case of the \var{-s} command-line option, the assembly file
  1656. will be left on disk, so the assembler can be called later. You can
  1657. disable the erasing of the assembler file with the \var{-a} switch.
  1658. The unit file contains all the information the compiler needs to use the
  1659. unit:
  1660. \begin{enumerate}
  1661. \item Other used units, both in interface and implementation.
  1662. \item Types and variables from the interface section of the unit.
  1663. \item Function declarations from the interface section of the unit.
  1664. \item Some debugging information, when compiled with debugging.
  1665. \end{enumerate}
  1666. The detailed contents and structure of this file are described in the first
  1667. appendix. You can examine a unit description file using the \file{ppudump}
  1668. program, which shows the contents of the file.
  1669. If you want to distribute a unit without source code, you must provide both
  1670. the unit description file and the object file.
  1671. You can also provide a C header file to go with the object file. In that
  1672. case, your unit can be used by someone who wishes to write his programs in
  1673. C. However, you must make this header file yourself since the \fpc compiler
  1674. doesn't make one for you.
  1675. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1676. % Programs
  1677. \section{Programs}
  1678. \label{se:Programs}
  1679. When you compile a program, the compiler produces again 2 files:
  1680. \begin{enumerate}
  1681. \item An assembly language file containing the statements of your program,
  1682. and memory allocations for all used variables.
  1683. \item A linker response file. This file contains a list of object files the
  1684. linker must link together.
  1685. \end{enumerate}
  1686. The link response file is, by default, removed from the disk. Only when you
  1687. specify the \var{-s} command-line option or when linking fails, then the file
  1688. is left on the disk. It is named \file{link.res}.
  1689. The assembly language file is converted to an object file by the assembler,
  1690. and then linked together with the rest of the units and a program header, to
  1691. form your final program.
  1692. The program header file is a small assembly program which provides the entry
  1693. point for the program. This is where the execution of your program starts,
  1694. so it depends on the operating system, because operating systems pass
  1695. parameters to executables in wildly different ways.
  1696. It's name is \file{prt0.o}, and the
  1697. source file resides in \file{prt0.as} or some variant of this name. It
  1698. usually resided where the system unit source for your system resides.
  1699. It's main function is to save the environment and command-line arguments and
  1700. set up the stack. Then it calls the main program.
  1701. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1702. % MMX Support
  1703. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1704. \chapter{Intel MMX support}
  1705. \label{ch:MMXSupport}
  1706. \section{What is it about?}
  1707. \label{se:WhatisMMXabout}
  1708. \fpc supports the new MMX (Multi-Media extensions)
  1709. instructions of Intel processors. The idea of MMX is to
  1710. process multiple data with one instruction, for example the processor
  1711. can add simultaneously 4 words. To implement this efficiently, the
  1712. Pascal language needs to be extended. So Free Pascal allows
  1713. to add for example two \var{array[0..3] of word},
  1714. if MMX support is switched on. The operation is done
  1715. by the \var{MMX} unit and allows people without assembler knowledge to take
  1716. advantage of the MMX extensions.
  1717. Here is an example:
  1718. \begin{verbatim}
  1719. uses
  1720. MMX; { include some predefined data types }
  1721. const
  1722. { tmmxword = array[0..3] of word;, declared by unit MMX }
  1723. w1 : tmmxword = (111,123,432,4356);
  1724. w2 : tmmxword = (4213,63456,756,4);
  1725. var
  1726. w3 : tmmxword;
  1727. l : longint;
  1728. begin
  1729. if is_mmx_cpu then { is_mmx_cpu is exported from unit mmx }
  1730. begin
  1731. {$mmx+} { turn mmx on }
  1732. w3:=w1+w2;
  1733. {$mmx-}
  1734. end
  1735. else
  1736. begin
  1737. for i:=0 to 3 do
  1738. w3[i]:=w1[i]+w2[i];
  1739. end;
  1740. end.
  1741. \end{verbatim}
  1742. \section{Saturation support}
  1743. \label{se:SaturationSupport}
  1744. One important point of MMX is the support of saturated operations.
  1745. If a operation would cause an overflow, the value stays at the
  1746. highest or lowest possible value for the data type:
  1747. If you use byte values you get normally 250+12=6. This is very
  1748. annoying when doing color manipulations or changing audio samples,
  1749. when you have to do a word add and check if the value is greater than
  1750. 255. The solution is saturation: 250+12 gives 255.
  1751. Saturated operations are supported by the \var{MMX} unit. If you
  1752. want to use them, you have simple turn the switch saturation on:
  1753. \var{\$saturation+}
  1754. Here is an example:
  1755. \begin{verbatim}
  1756. Program SaturationDemo;
  1757. {
  1758. example for saturation, scales data (for example audio)
  1759. with 1.5 with rounding to negative infinity
  1760. }
  1761. uses mmx;
  1762. var
  1763. audio1 : tmmxword;
  1764. i: smallint;
  1765. const
  1766. helpdata1 : tmmxword = ($c000,$c000,$c000,$c000);
  1767. helpdata2 : tmmxword = ($8000,$8000,$8000,$8000);
  1768. begin
  1769. { audio1 contains four 16 bit audio samples }
  1770. {$mmx+}
  1771. { convert it to $8000 is defined as zero, multiply data with 0.75 }
  1772. audio1:=(audio1+helpdata2)*(helpdata1);
  1773. {$saturation+}
  1774. { avoid overflows (all values>$7fff becomes $ffff) }
  1775. audio1:=(audio1+helpdata2)-helpdata2;
  1776. {$saturation-}
  1777. { now mupltily with 2 and change to integer }
  1778. for i:=0 to 3 do
  1779. audio1[i] := audio1[i] shl 1;
  1780. audio1:=audio1-helpdata2;
  1781. {$mmx-}
  1782. end.
  1783. \end{verbatim}
  1784. \section{Restrictions of MMX support}
  1785. \label{se:MMXrestrictions}
  1786. In the beginning of 1997 the MMX instructions were introduced in the
  1787. Pentium processors, so multitasking systems wouldn't save the
  1788. newly introduced MMX registers. To work around that problem, Intel
  1789. mapped the MMX registers to the FPU register.
  1790. The consequence is that
  1791. you can't mix MMX and floating point operations. After using
  1792. MMX operations and before using floating point operations, you
  1793. have to call the routine \var{EMMS} of the \var{MMX} unit.
  1794. This routine restores the FPU registers.
  1795. {\em Careful:} The compiler doesn't warn if you mix floating point and
  1796. MMX operations, so be careful.
  1797. The MMX instructions are optimized for multi media (what else?).
  1798. So it isn't possible to perform each operation, some operations
  1799. give a type mismatch, see section \ref{se:SupportedMMX} for the supported
  1800. MMX operations
  1801. An important restriction is that MMX operations aren't range or overflow
  1802. checked, even when you turn range and overflow checking on. This is due to
  1803. the nature of MMX operations.
  1804. The \var{MMX} unit must always be used when doing MMX operations
  1805. because the exit code of this unit clears the MMX unit. If it wouldn't do
  1806. that, other program will crash. A consequence of this is that you can't use
  1807. MMX operations in the exit code of your units or programs, since they would
  1808. interfere with the exit code of the \var{MMX} unit. The compiler can't
  1809. check this, so you are responsible for this!
  1810. \section{Supported MMX operations}
  1811. \label{se:SupportedMMX}
  1812. The following operations are supported in the compiler when MMX
  1813. extensions are enabled:
  1814. \begin{itemize}
  1815. \item addition (\var{+})
  1816. \item subtraction (\var{-})
  1817. \item multiplication(\var{*})
  1818. \item logical exclusive or (\var{xor})
  1819. \item logical and (\var{and})
  1820. \item logical or (\var{or})
  1821. \item sign change (\var{-})
  1822. \end{itemize}
  1823. \section{Optimizing MMX support}
  1824. \label{se:OptimizingMMX}
  1825. Here are some helpful hints to get optimal performance:
  1826. \begin{itemize}
  1827. \item The \var{EMMS} call takes a lot of time, so try to seperate floating
  1828. point and MMX operations.
  1829. \item Use MMX only in low level routines because the compiler
  1830. saves all used MMX registers when calling a subroutine.
  1831. \item The NOT-operator isn't supported natively by MMX, so the
  1832. compiler has to generate a workaround and this operation
  1833. is inefficient.
  1834. \item Simple assignements of floating point numbers don't access
  1835. floating point registers, so you need no call to the \var{EMMS}
  1836. procedure. Only when doing arithmetic, you need to call the \var{EMMS}
  1837. procedure.
  1838. \end{itemize}
  1839. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1840. % Code issues
  1841. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1842. \chapter{Code issues}
  1843. \label{ch:Code}
  1844. This chapter gives detailed information on the generated code by
  1845. \fpc. It can be useful to write external object files which will
  1846. be linked to \fpc created code blocks.
  1847. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1848. % Register conventions
  1849. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1850. \section{Register Conventions}
  1851. \label{se:RegConvs}
  1852. The compiler has different register conventions, depending on the
  1853. target processor used; some of the registers have specific uses
  1854. during the code generation. The following section describes the
  1855. generic names of the registers on a platform per platform basis. It
  1856. also indicates what registers are used as scratch registers, and
  1857. which can be freely used in assembler blocks.
  1858. \subsection{accumulator register}
  1859. The accumulator register is at least a 32-bit integer
  1860. hardware register, and is used to return results of
  1861. function calls which return integral values.
  1862. \subsection{accumulator 64-bit register}
  1863. The accumulator 64-bit register is used in 32-bit environments
  1864. and is defined as the group of registers which will be used when
  1865. returning 64-bit integral results in function calls. This is a
  1866. register pair.
  1867. \subsection{float result register}
  1868. This register is used for returning floating point values
  1869. from functions.
  1870. \subsection{self register}
  1871. The self register contains a pointer to the actual object or class.
  1872. This register gives access to the data of the object or class, and
  1873. the VMT pointer of that object or class.
  1874. \subsection{frame pointer register}
  1875. The frame pointer register is used to access parameters in subroutines,
  1876. as well as to access local variables. References to the pushed
  1877. prameters and local variables are constructed using the frame pointer.
  1878. \footnote{The frame pointer is not available on all platforms}.
  1879. \subsection{stack pointer register}
  1880. The stack pointer is used to give the address of the stack area,
  1881. where the local variables and parameters to subroutines are stored.
  1882. \subsection{scratch registers}
  1883. Scratch registers are those which can be used in assembler
  1884. blocks, or in external object files without requiring any saving
  1885. before usage.
  1886. \subsection{Processor mapping of registers}
  1887. This indicates what registers are used for what purposes
  1888. on each of the processors supported by \fpc. It also indicates
  1889. which registers can be used as scratch registers.
  1890. \subsubsection{Intel 80x86 version}
  1891. \begin{FPCltable}{ll}{Intel 80x86 Register table}{80x86Regs} \hline
  1892. Generic register name & CPU Register name \\ \hline
  1893. accumulator & EAX \\
  1894. accumulator (64-bit) high / low & EDX:EAX \\
  1895. float result & FP(0) \\
  1896. self & ESI \\
  1897. frame pointer & EBP \\
  1898. stack pointer & ESP \\
  1899. scratch regs. & N/A \\
  1900. \end{FPCltable}
  1901. \subsubsection{Motorola 680x0 version}
  1902. \begin{FPCltable}{ll}{Motorola 680x0 Register table}{680x0Regs} \hline
  1903. Generic register name & CPU Register name \\ \hline
  1904. accumulator & D0\footnotemark \\
  1905. accumulator (64-bit) high / low & D0:D1 \\
  1906. float result & FP0\footnotemark\\
  1907. self & A5 \\
  1908. frame pointer & A6 \\
  1909. stack pointer & A7 \\
  1910. scratch regs. & D0, D1, A0, A1, FP0, FP1 \\
  1911. \end{FPCltable}
  1912. \addtocounter{footnote}{-1}\footnotetext{For compatibility with some C compilers, when
  1913. the function result is a pointer and is declared with the cdecl convention,
  1914. the result is also stored in the A0 register}
  1915. \addtocounter{footnote}{1}\footnotetext{On simulated FPU's the result is returned in D0}
  1916. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1917. % Name mangling
  1918. \section{Name mangling}
  1919. \label{se:NameMangling}
  1920. Contrary to most C compilers and assemblers, all labels generated
  1921. to pascal variables and routines have mangled names\footnote{This can be avoided
  1922. by using the \var{alias} or \var{cdecl} modifiers}. This
  1923. is done so that the compiler can do stronger type checking when parsing
  1924. the pascal code. It also permits function and procedure overloading.
  1925. \subsection{Mangled names for data blocks}
  1926. The rules for mangled names for variables and typed constants
  1927. are as follows:
  1928. \begin{itemize}
  1929. \item All variable names are converted to upper case
  1930. \item Variables in the main program or private to a unit have an \_ prepended to their names
  1931. \item Typed constants in the main program have an TC\_\_ prepended to their names
  1932. \item Public variables in a unit have their unit name prepended to them : U\_UNITNAME\_
  1933. \item Public and private typed constants in a unit have their unit name prepended to them :TC\_\_UNITNAME\$\$
  1934. \end{itemize}
  1935. Currently, in \fpc v1.0, if you declare a variable in unit name \var{tunit},
  1936. with the name \var{\_a}, and you declare the same variable with name \var{a}
  1937. in unit name \var{tunit\_}, you will get the same mangled name. This is
  1938. a limitation of the compiler which will be fixed in release v1.1.
  1939. Examples
  1940. \begin{verbatim}
  1941. unit testvars;
  1942. interface
  1943. const
  1944. publictypedconst : integer = 0;
  1945. var
  1946. publicvar : integer;
  1947. implementation
  1948. const
  1949. privatetypedconst : integer = 1;
  1950. var
  1951. privatevar : integer;
  1952. end.
  1953. \end{verbatim}
  1954. Will give the following assembler output under GNU as :
  1955. \begin{verbatim}
  1956. .file "testvars.pas"
  1957. .text
  1958. .data
  1959. # [6] publictypedconst : integer = 0;
  1960. .globl TC__TESTVARS$$_PUBLICTYPEDCONST
  1961. TC__TESTVARS$$_PUBLICTYPEDCONST:
  1962. .short 0
  1963. # [12] privatetypedconst : integer = 1;
  1964. TC__TESTVARS$$_PRIVATETYPEDCONST:
  1965. .short 1
  1966. .bss
  1967. # [8] publicvar : integer;
  1968. .comm U_TESTVARS_PUBLICVAR,2
  1969. # [14] privatevar : integer;
  1970. .lcomm _PRIVATEVAR,2
  1971. \end{verbatim}
  1972. \subsection{Mangled names for code blocks}
  1973. The rules for mangled names for routines are as follows:
  1974. \begin{itemize}
  1975. \item All routine names are converted to upper case.
  1976. \item Routines in a unit have their unit name prepended to them : \_UNITNAME\$\$\_
  1977. \item All Routines in the main program have a \_ prepended to them.
  1978. \item All parameters in a routine are mangled using the type of the parameter
  1979. (in uppercase) prepended by the \$ character. This is done in left to right order
  1980. for each parameter of the routine.
  1981. \item Objects and classes use special mangling : The class type or object type
  1982. is given in the mangled name; The mangled name is as follows: \_\$\$\_TYPEDECL\_\$\$
  1983. optionally preceded by mangled name of the unit and finishing with the method
  1984. name.
  1985. \end{itemize}
  1986. The following constructs
  1987. \begin{verbatim}
  1988. unit testman;
  1989. interface
  1990. type
  1991. myobject = object
  1992. constructor init;
  1993. procedure mymethod;
  1994. end;
  1995. implementation
  1996. constructor myobject.init;
  1997. begin
  1998. end;
  1999. procedure myobject.mymethod;
  2000. begin
  2001. end;
  2002. function myfunc: pointer;
  2003. begin
  2004. end;
  2005. procedure myprocedure(var x: integer; y: longint; z : pchar);
  2006. begin
  2007. end;
  2008. end.
  2009. \end{verbatim}
  2010. will result in the following assembler file for the Intel 80x86 target:
  2011. \begin{verbatim}
  2012. .file "testman.pas"
  2013. .text
  2014. .balign 16
  2015. .globl _TESTMAN$$_$$_MYOBJECT_$$_INIT
  2016. _TESTMAN$$_$$_MYOBJECT_$$_INIT:
  2017. pushl %ebp
  2018. movl %esp,%ebp
  2019. subl $4,%esp
  2020. movl $0,%edi
  2021. call FPC_HELP_CONSTRUCTOR
  2022. jz .L5
  2023. jmp .L7
  2024. .L5:
  2025. movl 12(%ebp),%esi
  2026. movl $0,%edi
  2027. call FPC_HELP_FAIL
  2028. .L7:
  2029. movl %esi,%eax
  2030. testl %esi,%esi
  2031. leave
  2032. ret $8
  2033. .balign 16
  2034. .globl _TESTMAN$$_$$_MYOBJECT_$$_MYMETHOD
  2035. _TESTMAN$$_$$_MYOBJECT_$$_MYMETHOD:
  2036. pushl %ebp
  2037. movl %esp,%ebp
  2038. leave
  2039. ret $4
  2040. .balign 16
  2041. _TESTMAN$$_MYFUNC:
  2042. pushl %ebp
  2043. movl %esp,%ebp
  2044. subl $4,%esp
  2045. movl -4(%ebp),%eax
  2046. leave
  2047. ret
  2048. .balign 16
  2049. _TESTMAN$$_MYPROCEDURE$INTEGER$LONGINT$PCHAR:
  2050. pushl %ebp
  2051. movl %esp,%ebp
  2052. leave
  2053. ret $12
  2054. \end{verbatim}
  2055. \subsection{Modifying the mangled names}
  2056. To make the symbols externally accessible, it is possible to
  2057. give nicknames to mangled names, or to change the mangled
  2058. name directly. Two modifiers can be used:
  2059. \begin{description}
  2060. \item [cdecl:\ ] A function that has a \var{cdecl} modifier, will be used
  2061. with C calling conventions, that is, the caller clears the stack. Also
  2062. the mangled name will be the name {\em exactly} as it is declared.
  2063. \var{cdecl} is part of the function declaration, and hence must be present
  2064. both in the interface and implementation section of a unit.
  2065. \item [alias: ] The \var{alias} modifier can be used to assign a second
  2066. assembler label to your function. This label has the same name as the
  2067. alias name you declared. This doesn't modify the calling conventions
  2068. of the function. In other words, the \var{alias} modifier allows you to specify
  2069. another name (a nickname) for your function or procedure.
  2070. The prototype for an aliased function or procedure is as follows:
  2071. \begin{verbatim}
  2072. Procedure AliasedProc; alias : 'AliasName';
  2073. \end{verbatim}
  2074. The procedure \var{AliasedProc} will also be known as \var{AliasName}. Take
  2075. care, the name you specify is case sensitive (as C is).
  2076. \end{description}
  2077. Furthermore, the \var{exports} section of a library is also used to
  2078. declare the names that will be exported by the shared library. The
  2079. names in the exports section are case-sensitive (while the actual
  2080. declaration of the routine is not). For more information on the
  2081. creating shared libraries, \seec{libraries}.
  2082. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2083. % Calling mechanism
  2084. \section{Calling mechanism}
  2085. \label{se:CallingConventions}
  2086. Procedures and Functions are called with their parameters on the stack.
  2087. Contrary to Turbo Pascal, {\em all} parameters are pushed on the stack, and
  2088. they are pushed {\em right} to {\em left}, instead of left to right for
  2089. Turbo Pascal. This is especially important if you have some assembly
  2090. subroutines in Turbo Pascal which you would like to translate to \fpc.
  2091. Function results are returned in the accumulator, if they fit in the
  2092. register. Methods calls (from either objects or clases) have an additional
  2093. invisible parameter which is \var{self}. This parameter is the leftmost
  2094. parameter within a method call (it is therefore the last parameter passed
  2095. to the method).
  2096. When the procedure or function exits, it clears the stack.
  2097. Other calling methods are available for linking with
  2098. external object files and libraries, these are summarized in \seet{CallingTable}.
  2099. The first column lists the modifier you specify for a procedure declaration.
  2100. The second one lists the order the paramaters are pushed on the stack.
  2101. The third column specifies who is responsible for cleaning the stack:
  2102. the caller or the called function. The alignment column indicates the
  2103. alignment of the parameters sent to the stack area. Finally, the fifth
  2104. column indicates if any registers are saved in the entry code of the
  2105. subroutine.
  2106. \begin{FPCltable}{lllll}{Calling mechanisms in \fpc}{CallingTable}\hline
  2107. Modifier & Pushing order & Stack cleaned by & alignment & registers saved \\
  2108. \hline
  2109. <none> & Right-to-left & Function & default & None\\
  2110. cdecl & Right-to-left & Caller & GCC alignment & GCC registers\\
  2111. interrupt & Right-to-left & Function & default & all registers\\
  2112. pascal & Left-to-right & Function & default & None\\
  2113. safecall & Right-to-left & Function & default & GCC registers\\
  2114. stdcall & Right-to-left & Function & GCC alignment & GCC registers \\
  2115. popstack & Right-to-left & Caller & default & None \\
  2116. register & Left-to-right & Caller & default & None \\ \hline
  2117. \end{FPCltable}
  2118. More about this can be found in \seec{Linking} on linking. Information
  2119. on GCC registers saved, GCC stack alignment and general stack alignment
  2120. on an operating system basis can be found in Appendix \ref{ch:AppH}. The \var{register}
  2121. modifier is currently not supported, and maps to the default calling
  2122. convention.
  2123. Furthermore, the \var{saveregisters} modifier can be used with
  2124. any of the calling mechanism specifiers. When \var{saveregisters}
  2125. is used, all registers will be saved on entry to the routine,
  2126. and will be restored upon exit. Of course, if the routine is
  2127. a function, and it normally returns its retun value in a register,
  2128. that register will not be saved. Also, if the self register is
  2129. used, it will also neither be saved nor restored.
  2130. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2131. % Nested subroutines
  2132. \section{Nested procedure and functions}
  2133. \label{se:NestedRoutines}
  2134. When a routine is declared within the scope of a procedure or
  2135. function, it is said to be nested. In this case, an additional
  2136. invisible parameter is passed to the nested routine. This
  2137. additional parameter is the frame pointer address of the
  2138. calling routine. This permits the nested routine to access
  2139. the local variables and parameters of the calling routine.
  2140. The resulting stack frame after the entry code of a simple nested procedure
  2141. has been executed is shown in \seet{NestedStackFrame32}.
  2142. \begin{FPCltable}{ll}{Stack frame when calling a nested procedure (32-bit processors)}{NestedStackFrame32}
  2143. \hline
  2144. Offset from frame pointer & What is stored \\ \hline
  2145. +x & parameters\\
  2146. +8 & Frame pointer of parent routine\\
  2147. +4 & Return address\\
  2148. +0 & Saved frame pointer\\ \hline
  2149. \end{FPCltable}
  2150. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2151. % Constructor and destructor calls
  2152. \section{Constructor and Destructor calls}
  2153. \label{se:ConsDest}
  2154. Constructor and destructors have special invisible parameters
  2155. which are passed to them. These invisible parameters are used
  2156. internally to instanciate the objects and classes.
  2157. \subsection{objects}
  2158. The actual invisible declaration of an object constructoir
  2159. is as follows:
  2160. \begin{verbatim}
  2161. constructor init(_vmt : pointer; _self : pointer ...);
  2162. \end{verbatim}
  2163. Where \var{\_vmt} is a pointer to the virtual method table
  2164. for this object. This value is nil if a constructor is called
  2165. within the object instance (such as calling an ihnerited constructor).
  2166. \var{\_self} is either nil if the instance must be allocated
  2167. dynamically (object is declared as pointer), or the address of
  2168. the object instance if the object is declared as a normal object
  2169. (stored in the data area) or if the object instance has already
  2170. been allocated.
  2171. The allocated instance (if allocated via new) (\var{self})
  2172. is returned in the accumulator.
  2173. The declaration of a destructor is as follows:
  2174. \begin{verbatim}
  2175. destructor done(_vmt : pointer; _self : pointer ...);
  2176. \end{verbatim}
  2177. Where \var{\_vmt} is a pointer to the virtual method table
  2178. for this object. This value is nil if a destructor is called
  2179. within the object instance (such as calling an ihnerited constructor),
  2180. or if the object instance is a variable and not a pointer.
  2181. \var{\_self} is the address of the object instance.
  2182. \subsection{classes}
  2183. The actual invisible declaration of a class constructoir
  2184. is as follows:
  2185. \begin{verbatim}
  2186. constructor init(_vmt: pointer; flag : longint; ..);
  2187. \end{verbatim}
  2188. \var{\_vmt} is either nil if called from the instance
  2189. or if calling an inherited constructor, otherwise
  2190. it points to the address of the virtual method table.
  2191. Where \var{flag} is zero if the constructor is called
  2192. within the object instance or with an instance qualifier
  2193. otherwise this flag is set to one.
  2194. The allocated instance (\var{self}) is returned in the accumulator.
  2195. The declaration of a destructor is as follows:
  2196. \begin{verbatim}
  2197. destructor done(_self : pointer; flag : longint ...);
  2198. \end{verbatim}
  2199. \var{\_self} is the address of the object instance.
  2200. \var{flag} is zero if the destructor is called
  2201. within the object instance or with an instance qualifier
  2202. otherwise this flag is set to one.
  2203. \section{Entry and exit code}
  2204. Each Pascal procedure and function begins and ends with standard
  2205. epilogue and prologue code.
  2206. \subsection{Intel 80x86 standard routine prologue / epilogue}
  2207. Standard entry code for procedures and functions is as follows on the
  2208. 80x86 architecture:
  2209. \begin{verbatim}
  2210. pushl %ebp
  2211. movl %esp,%ebp
  2212. \end{verbatim}
  2213. The generated exit sequence for procedure and functions looks as follows:
  2214. \begin{verbatim}
  2215. leave
  2216. ret $xx
  2217. \end{verbatim}
  2218. Where \var{xx} is the total size of the pushed parameters.
  2219. To have more information on function return values take a look at
  2220. \sees{RegConvs}.
  2221. \subsection{Motorola 680x0 standard routine prologue / epilogue}
  2222. Standard entry code for procedures and functions is as follows on the
  2223. 680x0 architecture:
  2224. \begin{verbatim}
  2225. move.l a6,-(sp)
  2226. move.l sp,a6
  2227. \end{verbatim}
  2228. The generated exit sequence for procedure and functions looks as follows
  2229. (in the default processor mode):
  2230. \begin{verbatim}
  2231. unlk a6
  2232. rtd #xx
  2233. \end{verbatim}
  2234. Where \var{xx} is the total size of the pushed parameters.
  2235. To have more information on function return values take a look at
  2236. \sees{RegConvs}.
  2237. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2238. % Parameter passing
  2239. \section{Parameter passing}
  2240. \label{se:Parameters}
  2241. When a function or procedure is called, then the following is done by the
  2242. compiler:
  2243. \begin{enumerate}
  2244. \item If there are any parameters to be passed to the procedure, they are
  2245. pushed from right to left on the stack.
  2246. \item If a function is called that returns a variable of type \var{String},
  2247. \var{Set}, \var{Record}, \var{Object} or \var{Array}, then an address to
  2248. store the function result in, is pushed on the stack.
  2249. \item If the called procedure or function is an object method, then the
  2250. pointer to \var{self} is pushed on the stack.
  2251. \item If the procedure or function is nested in another function or
  2252. procedure, then the frame pointer of the parent procedure is pushed on the
  2253. stack.
  2254. \item The return address is pushed on the stack (This is done automatically
  2255. by the instruction which calls the subroutine).
  2256. \end{enumerate}
  2257. The resulting stack frame upon entering looks as in \seet{StackFrame}.
  2258. \begin{FPCltable}{llc}{Stack frame when calling a procedure (32-bit model)}{StackFrame}
  2259. \hline
  2260. Offset & What is stored & Optional? \\ \hline
  2261. +x & parameters & Yes \\
  2262. +12 & function result & Yes \\
  2263. +8 & self & Yes \\
  2264. +4 & Return address & No\\
  2265. +0 & Frame pointer of parent procedure & Yes \\ \hline
  2266. \end{FPCltable}
  2267. \subsection{Parameter alignment}
  2268. Each parameter passed to a routine is guaranteed to decrement the
  2269. stack pointer by a certain minimum amount. This behavior varies
  2270. from one operating system to another. For example, passing a
  2271. byte as a value parameter to a routine could either decrement the
  2272. stack pointer by 1, 2, 4 or even 8 bytes depending on the target
  2273. operating system and processor. The minimal default stack pointer decrement
  2274. value is given in Appendix \ref{ch:AppH}.
  2275. For example, on \freebsd, all parameters passed to a routine guarantee
  2276. a minimal stack decrease of four bytes per parameter, even if the
  2277. parameter actually takes less then 4 bytes to store on the stack (such
  2278. as passing a byte value parameter to the stack).
  2279. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2280. \section{Processor limitations}
  2281. \label{se:ProcessorLimits}
  2282. Certain processors have limitations on the size of the parameters
  2283. and local variables in routines. This is shown in \seet{CPULimits}.
  2284. \begin{FPCltable}{lll}{Maximum limits for processors}{CPULimits}
  2285. \hline
  2286. Processor & Parameters & Local variables \\ \hline
  2287. Intel 80x86 (all) & 64K & No limit\\
  2288. Motorola 68020 (default) & 32K & No limit\\
  2289. Motorola 68000 & 32K & 32K \\ \hline
  2290. \end{FPCltable}
  2291. Furthermore, the m68k compiler, in \var{68000} mode, limits the
  2292. size of data elements to 32K (arrays, records, objects, etc.).
  2293. This restriction does not exist in \var{68020} mode.
  2294. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2295. % Local variables
  2296. %\section{Local variables}
  2297. %\label{se:LocalVars}
  2298. %
  2299. % Stack alignment for local variables to complete -
  2300. % Currently the FPC version 1.0 stack alignment is
  2301. % simply too messy to describe consistently.
  2302. %
  2303. %
  2304. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2305. % Linking issues
  2306. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2307. \chapter{Linking issues}
  2308. \label{ch:Linking}
  2309. When you only use Pascal code, and Pascal units, then you will not see much
  2310. of the part that the linker plays in creating your executable.
  2311. The linker is only called when you compile a program. When compiling units,
  2312. the linker isn't invoked.
  2313. However, there are times that linking to C libraries, or to external
  2314. object files created by other compilers may be necessary. The \fpc compiler
  2315. can generate calls to a C function, and can generate functions that can
  2316. be called from C (exported functions).
  2317. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2318. % Using external code or variables
  2319. \section{Using external code and variables}
  2320. In general, there are 3 things you must do to use a function that resides in
  2321. an external library or object file:
  2322. \begin{enumerate}
  2323. \item You must make a pascal declaration of the function or procedure you
  2324. want to use.
  2325. \item You must declare the correct calling convention to use.
  2326. \item You must tell the compiler where the function resides, i.e. in what
  2327. object file or what library, so the compiler can link the necessary code in.
  2328. \end{enumerate}
  2329. The same holds for variables. To access a variable that resides in an
  2330. external object file, you must declare it, and tell the compiler where to
  2331. find it.
  2332. The following sections attempt to explain how to do this.
  2333. \subsection{Declaring external functions or procedures}
  2334. \label{se:ExternalFunction}
  2335. The first step in using external code blocks is declaring the function you
  2336. want to use. \fpc supports Delphi syntax, i.e. you must use the
  2337. \var{external} directive. The \var{external} directive replaces, in effect,
  2338. the code block of the function.
  2339. The external directive doesn't specify a calling convention; it just tells
  2340. the compiler that the code for a procedure or function resides in an
  2341. external code block. A calling convention modifier should be declared
  2342. if the external code blocks does not have the same calling conventions
  2343. as \fpc. For more information on the calling conventions
  2344. \sees{CallingConventions}.
  2345. There exist four variants of the external directive:
  2346. \begin{enumerate}
  2347. \item A simple external declaration:
  2348. \begin{verbatim}
  2349. Procedure ProcName (Args : TPRocArgs); external;
  2350. \end{verbatim}
  2351. The \var{external} directive tells the compiler that the function resides in
  2352. an external block of code. You can use this together with the \var{\{\$L\}}
  2353. or \var{\{\$LinkLib\}} directives to link to a function or procedure in a
  2354. library or external object file. Object files are looked for in the object
  2355. search path (set by \var{-Fo}) and libraries are searched for in the linker
  2356. path (set by \var{-Fl}).
  2357. \item You can give the \var{external} directive a library name as an
  2358. argument:
  2359. \begin{verbatim}
  2360. Procedure ProcName (Args : TPRocArgs); external 'Name';
  2361. \end{verbatim}
  2362. This tells the compiler that the procedure resides in a library with name
  2363. \var{'Name'}. This method is equivalent to the following:
  2364. \begin{verbatim}
  2365. Procedure ProcName (Args : TPRocArgs);external;
  2366. {$LinkLib 'Name'}
  2367. \end{verbatim}
  2368. \item The \var{external} can also be used with two arguments:
  2369. \begin{verbatim}
  2370. Procedure ProcName (Args : TPRocArgs); external 'Name'
  2371. name 'OtherProcName';
  2372. \end{verbatim}
  2373. This has the same meaning as the previous declaration, only the compiler
  2374. will use the name \var{'OtherProcName'} when linking to the library. This
  2375. can be used to give different names to procedures and functions in an
  2376. external library. The name of the routine is case-sensitive and should
  2377. match exactly the name of the routine in the object file.
  2378. This method is equivalent to the following code:
  2379. \begin{verbatim}
  2380. Procedure OtherProcName (Args : TProcArgs); external;
  2381. {$LinkLib 'Name'}
  2382. Procedure ProcName (Args : TPRocArgs);
  2383. begin
  2384. OtherProcName (Args);
  2385. end;
  2386. \end{verbatim}
  2387. \item Lastly, onder \windows and \ostwo, there is a fourth possibility
  2388. to specify an external function: In \file{.DLL} files, functions also have
  2389. a unique number (their index). It is possible to refer to these fuctions
  2390. using their index:
  2391. \begin{verbatim}
  2392. Procedure ProcName (Args : TPRocArgs); external 'Name' Index SomeIndex;
  2393. \end{verbatim}
  2394. This tells the compiler that the procedure \var{ProcName} resides in a
  2395. dynamic link library, with index {SomeIndex}.
  2396. \begin{remark}Note that this is ONLY available under \windows and \ostwo.
  2397. \end{remark}
  2398. \end{enumerate}
  2399. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2400. % Declaring an external variable
  2401. \subsection{Declaring external variables}
  2402. \label{se:ExternalVars}
  2403. Some libaries or code blocks have variables which they export. You can access
  2404. these variables much in the same way as external functions. To access an
  2405. external variable, you declare it as follows:
  2406. \begin{verbatim}
  2407. Var
  2408. MyVar : MyType; external name 'varname';
  2409. \end{verbatim}
  2410. The effect of this declaration is twofold:
  2411. \begin{enumerate}
  2412. \item No space is allocated for this variable.
  2413. \item The name of the variable used in the assembler code is \var{varname}.
  2414. This is a case sensitive name, so you must be careful.
  2415. \end{enumerate}
  2416. The variable will be
  2417. accessible with it's declared name, i.e. \var{MyVar} in this case.
  2418. A second possibility is the declaration:
  2419. \begin{verbatim}
  2420. Var
  2421. varname : MyType; cvar; external;
  2422. \end{verbatim}
  2423. The effect of this declaration is twofold as in the previous case:
  2424. \begin{enumerate}
  2425. \item The \var{external} modifier ensures that no space is allocated for
  2426. this variable.
  2427. \item The \var{cvar} modifier tells the compiler that the name of the
  2428. variable used in the assembler code is exactly as specified in the
  2429. declaration. This is a case sensitive name, so you must be careful.
  2430. \end{enumerate}
  2431. The first possibility allows you to change the name of the
  2432. external variable for internal use.
  2433. As an example, let's look at the following C file (in \file{extvar.c}):
  2434. \begin{verbatim}
  2435. /*
  2436. Declare a variable, allocate storage
  2437. */
  2438. int extvar = 12;
  2439. \end{verbatim}
  2440. And the following program (in \file{extdemo.pp}):
  2441. \begin{verbatim}
  2442. Program ExtDemo;
  2443. {$L extvar.o}
  2444. Var { Case sensitive declaration !! }
  2445. extvar : longint; cvar;external;
  2446. I : longint; external name 'extvar';
  2447. begin
  2448. { Extvar can be used case insensitive !! }
  2449. Writeln ('Variable ''extvar'' has value: ',ExtVar);
  2450. Writeln ('Variable ''I'' has value: ',i);
  2451. end.
  2452. \end{verbatim}
  2453. Compiling the C file, and the pascal program:
  2454. \begin{verbatim}
  2455. gcc -c -o extvar.o extvar.c
  2456. ppc386 -Sv extdemo
  2457. \end{verbatim}
  2458. Will produce a program \file{extdemo} which will print
  2459. \begin{verbatim}
  2460. Variable 'extvar' has value: 12
  2461. Variable 'I' has value: 12
  2462. \end{verbatim}
  2463. on your screen.
  2464. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2465. % Declaring the calling conventions
  2466. \subsection{Declaring the calling convention modifier}
  2467. To make sure that all parameters are correctly passed to the
  2468. external routines, you should declare it with the correct
  2469. calling convention modifier. When linking with code blocks
  2470. compiled with standard C compilers (such as GCC), the \var{cdecl}
  2471. modifier should be used so as to indicate that the external
  2472. routine uses C type calling conventions. For more information
  2473. on the supported calling conventions, \sees{CallingConventions}.
  2474. As might expected, external variable declarations do not require
  2475. any calling convention modifier.
  2476. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2477. % Linking an object file in your program
  2478. \subsection{Declaring the external object code}
  2479. \subsubsection{Linking to an object file}
  2480. \label{se:LinkIn}
  2481. Having declared the external function or variable that resides in an object file,
  2482. you can use it as if it was defined in your own program or unit.
  2483. To produce an executable, you must still link the object file in.
  2484. This can be done with the \var{\{\$L file.o\}} directive.
  2485. This will cause the linker to link in the object file \file{file.o}. On
  2486. most systems, this filename is case sensitive. The object file is
  2487. first searched in the current directory, and then the directories specified
  2488. by the \var{-Fo} command line.
  2489. You cannot specify libraries in this way, it is for object files only.
  2490. Here we present an example. Consider that you have some assembly routine which uses
  2491. the C calling convention that calculates the nth Fibonacci number:
  2492. \begin{verbatim}
  2493. .text
  2494. .align 4
  2495. .globl Fibonacci
  2496. .type Fibonacci,@function
  2497. Fibonacci:
  2498. pushl %ebp
  2499. movl %esp,%ebp
  2500. movl 8(%ebp),%edx
  2501. xorl %ecx,%ecx
  2502. xorl %eax,%eax
  2503. movl $1,%ebx
  2504. incl %edx
  2505. loop:
  2506. decl %edx
  2507. je endloop
  2508. movl %ecx,%eax
  2509. addl %ebx,%eax
  2510. movl %ebx,%ecx
  2511. movl %eax,%ebx
  2512. jmp loop
  2513. endloop:
  2514. movl %ebp,%esp
  2515. popl %ebp
  2516. ret
  2517. \end{verbatim}
  2518. Then you can call this function with the following Pascal Program:
  2519. \begin{verbatim}
  2520. Program FibonacciDemo;
  2521. var i : longint;
  2522. Function Fibonacci (L : longint):longint;cdecl;external;
  2523. {$L fib.o}
  2524. begin
  2525. For I:=1 to 40 do
  2526. writeln ('Fib(',i,') : ',Fibonacci (i));
  2527. end.
  2528. \end{verbatim}
  2529. With just two commands, this can be made into a program:
  2530. \begin{verbatim}
  2531. as -o fib.o fib.s
  2532. ppc386 fibo.pp
  2533. \end{verbatim}
  2534. This example supposes that you have your assembler routine in \file{fib.s},
  2535. and your Pascal program in \file{fibo.pp}.
  2536. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2537. % Linking your program to a library
  2538. \subsubsection{Linking to a library}
  2539. \label{se:LinkOut}
  2540. To link your program to a library, the procedure depends on how you declared
  2541. the external procedure.
  2542. In case you used the following syntax to declare your procedure:
  2543. \begin{verbatim}
  2544. Procedure ProcName (Args : TPRocArgs); external 'Name';
  2545. \end{verbatim}
  2546. You don't need to take additional steps to link your file in, the compiler
  2547. will do all that is needed for you. On \windows it will link to
  2548. \file{name.dll}, on \linux and most \unix'es your program will be linked to library
  2549. \file{libname}, which can be a static or dynamic library.
  2550. In case you used
  2551. \begin{verbatim}
  2552. Procedure ProcName (Args : TPRocArgs); external;
  2553. \end{verbatim}
  2554. You still need to explicity link to the library. This can be done in 2 ways:
  2555. \begin{enumerate}
  2556. \item You can tell the compiler in the source file what library to link to
  2557. using the \var{\{\$LinkLib 'Name'\}} directive:
  2558. \begin{verbatim}
  2559. {$LinkLib 'gpm'}
  2560. \end{verbatim}
  2561. This will link to the \file{gpm} library. On \unix systems (such as \linux),
  2562. you must not specify the extension or 'lib' prefix of the library. The compiler takes
  2563. care of that. On other systems (such as \windows, you need to specify the full
  2564. name.
  2565. \item You can also tell the compiler on the command-line to link in a
  2566. library: The \var{-k} option can be used for that. For example
  2567. \begin{verbatim}
  2568. ppc386 -k'-lgpm' myprog.pp
  2569. \end{verbatim}
  2570. Is equivalent to the above method, and tells the linker to link to the
  2571. \file{gpm} library.
  2572. \end{enumerate}
  2573. As an example; consider the following program:
  2574. \begin{verbatim}
  2575. program printlength;
  2576. {$linklib c} { Case sensitive }
  2577. { Declaration for the standard C function strlen }
  2578. Function strlen (P : pchar) : longint; cdecl;external;
  2579. begin
  2580. Writeln (strlen('Programming is easy !'));
  2581. end.
  2582. \end{verbatim}
  2583. This program can be compiled with:
  2584. \begin{verbatim}
  2585. ppc386 prlen.pp
  2586. \end{verbatim}
  2587. Supposing, of course, that the program source resides in \file{prlen.pp}.
  2588. To use functions in C that have a variable number of arguments, you must
  2589. compile your unit or program in \var{objfpc} mode or \var{Delphi} mode,
  2590. and use the \var{Array of const} argument, as in the following example:
  2591. \begin{verbatim}
  2592. program testaocc;
  2593. {$mode objfpc}
  2594. Const
  2595. P : Pchar
  2596. = 'example';
  2597. F : Pchar
  2598. = 'This %s uses printf to print numbers (%d) and strings.'#10;
  2599. procedure printf(fm: pchar;args: array of const);cdecl;external 'c';
  2600. begin
  2601. printf(F,[P,123]);
  2602. end.
  2603. \end{verbatim}
  2604. The output of this program looks like this:
  2605. \begin{verbatim}
  2606. This example uses printf to print numbers (123) and strings.
  2607. \end{verbatim}
  2608. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2609. % Making a library
  2610. \section{Making libraries}
  2611. \label{se:StaticLib}
  2612. \fpc supports making shared or static libraries in a straightforward and
  2613. easy manner. If you want to make static libraries for other \fpc programmers,
  2614. you just need to provide a command line switch. To make shared libraries,
  2615. refer to the \seec{libraries}. If you want C programmers to be able to use your
  2616. code as well, you will need to adapt your code a little. This process
  2617. is described first.
  2618. % Exporting functions.
  2619. \subsection{Exporting functions}
  2620. When exporting functions from a library, there are 2 things you must take in
  2621. account:
  2622. \begin{enumerate}
  2623. \item Calling conventions.
  2624. \item Naming scheme.
  2625. \end{enumerate}
  2626. The calling conventions are controlled by the modifiers \var{cdecl},
  2627. \var{popstack}, \var{pascal}, \var{safecall}, \var{stdcall} and
  2628. \var{register}. See \sees{CallingConventions} for more information on the
  2629. different kinds of calling scheme.
  2630. The naming conventions can be controlled by 2 modifiers in the case
  2631. of static libraries:
  2632. \begin{itemize}
  2633. \item \var{cdecl}
  2634. \item \var{alias}
  2635. \end{itemize}
  2636. For more information on how these different modifiers change the name
  2637. mangling of the routine \sees{NameMangling}.
  2638. \begin{remark}If you use in your unit functions that are in other units, or
  2639. system functions, then the C program will need to link in the object files
  2640. from these units too.
  2641. \end{remark}
  2642. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2643. % Exporting variables.
  2644. \subsection{Exporting variables}
  2645. Similarly as when you export functions, you can export variables.
  2646. When exportig variables, one should only consider the names of the
  2647. variables. To declare a variable that should be used by a C program,
  2648. one declares it with the \var{cvar} modifier:
  2649. \begin{verbatim}
  2650. Var MyVar : MyTpe; cvar;
  2651. \end{verbatim}
  2652. This will tell the compiler that the assembler name of the variable (the one
  2653. which is used by C programs) should be exactly as specified in the
  2654. declaration, i.e., case sensitive.
  2655. It is not allowed to declare multiple variables as \var{cvar} in one
  2656. statement, i.e. the following code will produce an error:
  2657. \begin{verbatim}
  2658. var Z1,Z2 : longint;cvar;
  2659. \end{verbatim}
  2660. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2661. % Compiling libraries
  2662. \subsection {Compiling libraries}
  2663. Once you have your (adapted) code, with exported and other functions,
  2664. you can compile your unit, and tell the compiler to make it into a library.
  2665. The compiler will simply compile your unit, and perform the necessary steps
  2666. to transform it into a \var{static} or \var{shared} (\var{dynamic}) library.
  2667. You can do this as follows, for a dynamic library:
  2668. \begin{verbatim}
  2669. ppc386 -CD myunit
  2670. \end{verbatim}
  2671. On \unix systems, such as \linux, this will leave you with a file \file{libmyunit.so}. On \windows
  2672. and \ostwo, this will leave you with \file{myunit.dll}. An easier way to
  2673. create shared libraries is to use the \var{library} keyword. For more
  2674. information on creating shared libraries, \seec{libraries}.
  2675. If you want a static library, you can do
  2676. \begin{verbatim}
  2677. ppc386 -CS myunit
  2678. \end{verbatim}
  2679. This will leave you with \file{libmyunit.a} and a file \file{myunit.ppu}.
  2680. The \file{myunit.ppu} is the unit file needed by the \fpc compiler.
  2681. The resulting files are then libraries. To make static libraries, you need
  2682. the \file{ranlib} or \var{ar} program on your system. It is standard on most
  2683. \unix systems, and is provided with the \file{gcc} compiler under \dos.
  2684. For the dos distribution, a copy of ar is included in the file
  2685. \file{gnuutils.zip}.
  2686. {\em BEWARE:} This command doesn't include anything but the current unit in
  2687. the library. Other units are left out, so if you use code from other units,
  2688. you must deploy them together with your library.
  2689. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2690. % unit searching
  2691. \subsection{Unit searching strategy}
  2692. When you compile a unit, the compiler will by
  2693. default always look for unit files.
  2694. To be able to differentiate between units that have been compiled as static
  2695. or dynamic libraries, there are 2 switches:
  2696. \begin{description}
  2697. \item [-XD:\ ] This will define the symbol \var{FPC\_LINK\_DYNAMIC}
  2698. \item [-XS:\ ] This will define the symbol \var{FPC\_LINK\_STATIC}
  2699. \end{description}
  2700. Definition of one symbol will automatically undefine the other.
  2701. These two switches can be used in conjunction with the configuration file
  2702. \file{fpc.cfg}. The existence of one of these symbols can be used to
  2703. decide which unit search path to set. For example, on \linux:
  2704. \begin{verbatim}
  2705. # Set unit paths
  2706. #IFDEF FPC_LINK_STATIC
  2707. -Up/usr/lib/fpc/linuxunits/staticunits
  2708. #ENDIF
  2709. #IFDEF FPC_LINK_DYNAMIC
  2710. -Up/usr/lib/fpc/linuxunits/sharedunits
  2711. #ENDIF
  2712. \end{verbatim}
  2713. With such a configuration file, the compiler will look for it's units in
  2714. different directories, depending on whether \var{-XD} or \var{-XS} is used.
  2715. \section{Using smart linking}
  2716. \label{se:SmartLinking}
  2717. You can compile your units using smart linking. When you use smartlinking,
  2718. the compiler creates a series of code blocks that are as small as possible,
  2719. i.e. a code block will contain only the code for one procedure or function.
  2720. When you compile a program that uses a smart-linked unit, the compiler will
  2721. only link in the code that you actually need, and will leave out all other
  2722. code. This will result in a smaller binary, which is loaded in memory
  2723. faster, thus speeding up execution.
  2724. To enable smartlinking, one can give the smartlink option on the command
  2725. line: \var{-Cx}, or one can put the \var{\{\$SMARTLINK ON\}} directive in
  2726. the unit file:
  2727. \begin{verbatim}
  2728. Unit Testunit
  2729. {SMARTLINK ON}
  2730. Interface
  2731. ...
  2732. \end{verbatim}
  2733. Smartlinking will slow down the compilation process, especially for large
  2734. units.
  2735. When a unit \file{foo.pp} is smartlinked, the name of the codefile is
  2736. changed to \file{libfoo.a}.
  2737. Technically speaking, the compiler makes small assembler files for each
  2738. procedure and function in the unit, as well as for all global defined
  2739. variables (whether they're in the interface section or not). It then
  2740. assembles all these small files, and uses \file{ar} to collect the resulting
  2741. object files in one archive.
  2742. Smartlinking and the creation of shared (or dynamic) libraries are mutually
  2743. exclusive, that is, if you turn on smartlinking, then the creation of shared
  2744. libraries is turned of. The creation of static libraries is still possible.
  2745. The reason for this is that it has little sense in making a smartlinked
  2746. dynamical library. The whole shared library is loaded into memory anyway by
  2747. the dynamic linker (or the operating system), so there would be no gain in size by
  2748. making it smartlinked.
  2749. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2750. % Memory issues
  2751. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2752. \chapter{Memory issues}
  2753. \label{ch:Memory}
  2754. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2755. % The memory model
  2756. \section{The memory model.}
  2757. \label{se:ThirtytwoBit}
  2758. The \fpc compiler issues 32-bit or 64-bit code.
  2759. This has several consequences:
  2760. \begin{itemize}
  2761. \item You need a 32-bit or 64-bit processor to run the generated code. The
  2762. compiler functions on a 286 when you compile it using Turbo Pascal,
  2763. but the generated programs cannot be assembled or executed.
  2764. \item You don't need to bother with segment selectors. Memory can be
  2765. addressed using a single 32-bit (on 32-bit processors) or 64-bit (on
  2766. 64-bit processors with 64-bit addressing) pointer.
  2767. The amount of memory is limited only by the available amount of (virtual)
  2768. memory on your machine.
  2769. \item The structures you define are unlimited in size. Arrays can be as long
  2770. as you want. You can request memory blocks from any size.
  2771. \end{itemize}
  2772. The fact that 16-bit code is no longer used, means that some of the older
  2773. Turbo Pascal constructs and functions are obsolete. The following is a
  2774. list of functions which shouldn't be used anymore:
  2775. \begin{description}
  2776. \item [Seg()]: Returned the segment of a memory address. Since segments have
  2777. no more meaning, zero is returned in the \fpc run-time library implementation of
  2778. \var{Seg}.
  2779. \item [Ofs()]: Returned the offset of a memory address. Since segments have
  2780. no more meaning, the complete address is returned in the \fpc implementation
  2781. of this function. This has as a consequence that the return type is
  2782. \var{longint} or \var{int64} instead of \var{Word}.
  2783. \item [Cseg(), Dseg()]: Returned, respectively, the code and data segments
  2784. of your program. This returns zero in the \fpc implementation of the
  2785. system unit, since both code and data are in the same memory space.
  2786. \item [Ptr]: Accepted a segment and offset from an address, and would return
  2787. a pointer to this address. This has been changed in the run-time library, it
  2788. now simply returns the offset.
  2789. \item [memw and mem]: These arrays gave access to the \dos memory. \fpc
  2790. supports them on the go32v2 platform, they are mapped into \dos memory
  2791. space. You need the \file{go32} unit for this. On other platforms, they are
  2792. {\em not} supported
  2793. \end{description}
  2794. You shouldn't use these functions, since they are very non-portable, they're
  2795. specific to \dos and the 80x86 processor. The \fpc compiler is designed to be
  2796. portable to other platforms, so you should keep your code as portable as
  2797. possible, and not system specific. That is, unless you're writing some driver
  2798. units, of course.
  2799. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2800. % Data formats
  2801. \section{Data formats}
  2802. \label{se:Dataformats}
  2803. This section gives information on the storage space occupied by
  2804. the different possible types in \fpc. Information on internal
  2805. alignment will also be given.
  2806. \subsection{integer types}
  2807. The storage size of the default integer types are given in
  2808. \refref. In the case of user defined-types, the storage space
  2809. occupied depends on the bounds of the type:
  2810. \begin{itemize}
  2811. \item If both bounds are within range -128..127, the variable
  2812. is stored as a shortint (signed 8-bit quantity).
  2813. \item If both bounds are within the range 0..255, the variable
  2814. is stored as a byte (unsigned 8-bit quantity).
  2815. \item If both bounds are within the range -32768..32767, the variable
  2816. is stored as a smallint (signed 16-bit quantity).
  2817. \item If both bounds are within the range 0..65535, the variable
  2818. is stored as a word (unsigned 16-bit quantity)
  2819. \item If both bounds are within the range 0..4294967295, the
  2820. variable is stored as a longword (unsigned 32-bit quantity).
  2821. \item Otherwise the variable is stored as a longint (signed
  2822. 32-bit quantity).
  2823. \end{itemize}
  2824. \subsection{char types}
  2825. A \var{char}, or a subrange of the char type is stored
  2826. as a byte.
  2827. \subsection{boolean types}
  2828. The \var{boolean} type is stored as a byte and can take
  2829. a value of \var{true} or \var{false}.
  2830. A \var{ByteBool} is stored as a byte, a \var{WordBool}
  2831. type is stored as a word, and a \var{longbool} is stored
  2832. as a longint.
  2833. \subsection{enumeration types}
  2834. By default all enumerations are stored as a
  2835. longword (4 bytes), which is equivalent to specifying
  2836. the \var{\{\$Z4\}}, \var{\{\$PACKENUM 4\}} or
  2837. \var{\{\$PACKENUM DEFAULT\}} switches.
  2838. This default behavior can be changed by compiler switches,
  2839. and by the compiler mode.
  2840. In the \var{tp} compiler mode, or while the \var{\{\$Z1\}} or
  2841. \var{\{\$PACKENUM 1\}} switches are in effect, the storage
  2842. space used is shown in \seet{enumstoragetp}.
  2843. \begin{FPCltable}{ll}{Enumeration storage for \var{tp} mode}{enumstoragetp}
  2844. \# Of Elements in Enum. & Storage space used\\ \hline
  2845. 0..255 & byte (1 byte) \\
  2846. 256..65535 & word (2 bytes) \\
  2847. > 65535 & longword (4 bytes) \\
  2848. \hline
  2849. \end{FPCltable}
  2850. When the \var{\{\$Z2\}} or \var{\{\$PACKENUM 2\}}
  2851. switches are in effect, the value is stored on 2
  2852. bytes (word), if the enumeration has less or equal
  2853. then 65535 elements, otherwise, the enumeration
  2854. value is stored as a 4 byte value (longword).
  2855. \subsection{floating point types}
  2856. Floating point type sizes and mapping vary from one
  2857. processor to another. Except for the Intel 80x86
  2858. architecture, the \var{extended} type maps to the IEEE
  2859. double type.
  2860. \begin{FPCltable}{lr}{Processor mapping of real type}{RealMapping}
  2861. Processor & Real type mapping\\
  2862. \hline
  2863. Intel 80x86 & \var{double}\\
  2864. Motorola 680x0 (with \{\$E-\} switch) & \var{double}\\
  2865. Motorola 680x0 (with \{\$E+\} switch) & \var{single}\\
  2866. \hline
  2867. \end{FPCltable}
  2868. Floating point types have a storage binary format divided
  2869. into three distinct fields : the mantissa, the exponent
  2870. and the sign bit which stores the sign of the floating
  2871. point value.
  2872. \subsubsection{single}
  2873. The \var{single} type occupies 4 bytes of storage space,
  2874. and its memory structure is the same as the IEEE-754 single
  2875. type.
  2876. The memory format of the \var{single} format looks like
  2877. \begin{htmlonly}
  2878. this:
  2879. \fpcaddimg{../pics/single.png}
  2880. \end{htmlonly}
  2881. \begin{latexonly}
  2882. what is shown in \seefig{singleformat}.
  2883. \begin{figure}
  2884. \caption{The single format}
  2885. \label{fig:singleformat}
  2886. \begin{center}
  2887. \ifpdf
  2888. \epsfig{file=pics/single.png}
  2889. \else
  2890. \epsfig{file=pics/single.eps}
  2891. \fi
  2892. \end{center}
  2893. \end{figure}
  2894. \end{latexonly}
  2895. \subsubsection{double}
  2896. The \var{double} type occupies 8 bytes of storage space,
  2897. and its memory structure is the same as the IEEE-754 double
  2898. type.
  2899. The memory format of the \var{double} format looks like
  2900. \begin{htmlonly}
  2901. this:
  2902. \fpcaddimg{../pics/double.png}
  2903. \end{htmlonly}
  2904. \begin{latexonly}
  2905. like what is shown in \seefig{doubleformat}.
  2906. \begin{figure}
  2907. \begin{center}
  2908. \caption{The double format}
  2909. \label{fig:doubleformat}
  2910. \ifpdf
  2911. \epsfig{file=pics/double.png}
  2912. \else
  2913. \epsfig{file=pics/double.eps}
  2914. \fi
  2915. \end{center}
  2916. \end{figure}
  2917. \end{latexonly}
  2918. On processors which do not support co-processor operations (and which have
  2919. the \{\$E-\} switch), the \var{double} type does not exist.
  2920. \subsubsection{extended}
  2921. For Intel 80x86 processors, the \var{extended} type has
  2922. takes up 10 bytes of memory space. For more information
  2923. on the extended type consult the Intel Programmer's reference.
  2924. For all other processors which support floating point operations,
  2925. the \var{extended} type is a nickname for the \var{double} type.
  2926. It has the same format and size as the \var{double} type. On
  2927. processors which do not support co-processor operations (and which have
  2928. the \{\$E-\} switch), the
  2929. \var{extended} type does not exist.
  2930. \subsubsection{comp}
  2931. For Intel 80x86 processors, the \var{comp} type contains
  2932. a 63-bit integral value, and a sign bit (in the MSB position).
  2933. The \var{comp} type takes up 8 bytes of storage space.
  2934. On other processors, the \var{comp} type is not supported.
  2935. \subsubsection{real}
  2936. Contrary to Turbo Pascal, where the \var{real} type had
  2937. a special internal format, under \fpc the \var{real} type
  2938. simply maps to one of the other real types. It maps to the
  2939. \var{double} type on processors which support floating
  2940. point operations, while it maps to the \var{single} type
  2941. on processors which do not support floating point operations
  2942. in hardware. See \seet{RealMapping} for more information
  2943. on this.
  2944. \subsection{pointer types}
  2945. A \var{pointer} type is stored as a longword (unsigned 32-bit value) on
  2946. 32-bit processors, and is stored as a 64-bit unsigned value\footnote{this
  2947. is actually the \var{qword} type, which is not supported in \fpc v1.0}
  2948. on 64-bit processors.
  2949. \subsection{string types}
  2950. \subsubsection{ansistring types}
  2951. The ansistring is a dynamically allocated string which
  2952. has no length limitation. When the string is no longer
  2953. being referenced (its reference count reaches zero),
  2954. its memory is automatically freed.
  2955. If the ansistring is a constant, then its reference
  2956. count will be equal to -1, indicating that it should
  2957. never be freed. The structure in memory for an
  2958. ansistring is shown in \seet{ansistrings}.
  2959. \begin{FPCltable}{rl}{AnsiString memory structure (32-bit model)}{ansistrings}
  2960. Offset & Contains \\ \hline
  2961. -12 & Longint with maximum string size. \\
  2962. -8 & Longint with actual string size.\\
  2963. -4 & Longint with reference count.\\
  2964. 0 & Actual array of \var{char}, null-terminated. \\ \hline
  2965. \end{FPCltable}
  2966. \subsubsection{shortstring types}
  2967. A shortstring occupies as many bytes as its maximum length plus one.
  2968. The first byte contains the current dynamic length of the string. The
  2969. following bytes contain the actual characters (of type \var{char})
  2970. of the string. The maximum size of a short string is the length
  2971. byte followed by 255 characters.
  2972. \subsubsection{widestring types}
  2973. The widestring (composed of unicode characters) is not supported
  2974. in \fpc v1.0.
  2975. \subsection{set types}
  2976. A set is stored as an array of bits, where each bit indicates
  2977. if the element is in the set or excluded from the set. The maximum
  2978. number of elements in a set is 256.
  2979. If a set has less than 32 elements, it is coded as an unsigned
  2980. 32-bit value. Otherwise it is coded as a 8 element array of
  2981. 32-bit unsigned values (longword) (hence a size of 256 bytes).
  2982. The longword number of a specific element \var{E} is given by :
  2983. \begin{verbatim}
  2984. LongwordNumber = (E div 32);
  2985. \end{verbatim}
  2986. and the bit number within that 32-bit value is given by:
  2987. \begin{verbatim}
  2988. BitNumber = (E mod 32);
  2989. \end{verbatim}
  2990. \subsection{array types}
  2991. An array is stored as a contiguous sequence of variables
  2992. of the components of the array. The components with the
  2993. lowest indexes are stored first in memory. No alignment
  2994. is done between each element of the array. A multi-dimensional
  2995. array is stored with the rightmost dimension increasing first.
  2996. \subsection{record types}
  2997. Each field of a record are stored in a contigous sequence
  2998. of variables, where the first field is stored at the
  2999. lowest address in memory. In case of variant fields in
  3000. a record, each variant starts at the same address in
  3001. memory. Fields of record are usually aligned, unless
  3002. the \var{packed} directive is specified when declaring
  3003. the record type. For more information on field alignment,
  3004. consult \sees{StructuredAlignment}.
  3005. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3006. % memory storage of Objects
  3007. \subsection{object types}
  3008. \label{subse:ObjMemory}
  3009. Objects are stored in memory just as ordinary records with an extra field:
  3010. a pointer to the Virtual Method Table (VMT). This field is stored first, and
  3011. all fields in the object are stored in the order they are declared (with possible
  3012. alignment of field addresses, unless the object was declared as being \var{packed}).
  3013. This field is initialized by the call to the object's \var{Constructor} method.
  3014. If the \var{new} operator was used to call the constructor, the data fields
  3015. of the object will be stored in heap memory, otherwise they will directly
  3016. be stored in the data section of the final executable.
  3017. If an object doesn't have virtual methods, no pointer to a VMT is inserted.
  3018. The memory allocated looks as in \seet{ObjMem}.
  3019. \begin{FPCltable}{ll}{Object memory layout (32-bit model)}{ObjMem} \hline
  3020. Offset & What \\ \hline
  3021. +0 & Pointer to VMT (optional). \\
  3022. +4 & Data. All fields in the order the've been declared. \\
  3023. \dots & \\
  3024. \hline
  3025. \end{FPCltable}
  3026. The Virtual Method Table (VMT) for each object type consists of 2 check
  3027. fields (containing the size of the data), a pointer to the object's ancestor's
  3028. VMT (\var{Nil} if there is no ancestor), and then the pointers to all virtual
  3029. methods. The VMT layout is illustrated in \seet{ObjVMTMem}. The VMT is
  3030. constructed by the compiler.
  3031. \begin{FPCltable}{ll}{Object Virtual Method Table memory layout (32-bit model)}{ObjVMTMem} \hline
  3032. Offset & What \\ \hline
  3033. +0 & Size of object type data \\
  3034. +4 & Minus the size of object type data. Enables determining of valid VMT
  3035. pointers. \\
  3036. +8 & Pointer to ancestor VMT, \var{Nil} if no ancestor available.\\
  3037. +12 & Pointers to the virtual methods. \\
  3038. \dots & \\
  3039. \hline
  3040. \end{FPCltable}
  3041. \subsection{class types}
  3042. Just like objects, classes are stored in memory just as ordinary records
  3043. with an extra field: a pointer to the Virtual Method Table (VMT).
  3044. This field is stored first, and all fields in the class are stored in
  3045. the order they are declared.
  3046. Contrary to objects, all data fields of a class are always stored
  3047. in heap memory.
  3048. The memory allocated looks as in \seet{ClassMem}.
  3049. \begin{FPCltable}{ll}{Class memory layout (32-bit model)}{ClassMem} \hline
  3050. Offset & What \\ \hline
  3051. +0 & Pointer to VMT. \\
  3052. +4 & Data. All fields in the order the've been declared. \\
  3053. \dots & \\
  3054. \hline
  3055. \end{FPCltable}
  3056. The Virtual Method Table (VMT) of each class consists of several fields,
  3057. which are used for runtime type information. The VMT layout is illustrated
  3058. in \seet{ClassVMTMem}. The VMT is constructed by the compiler.
  3059. \begin{FPCltable}{ll}{Class Virtual Method Table memory layout (32-bit model)}{ClassVMTMem} \hline
  3060. Offset & What \\ \hline
  3061. +0 & Size of object type data \\
  3062. +4 & Minus the size of object type data. Enables determining of valid VMT
  3063. pointers. \\
  3064. +8 & Pointer to ancestor VMT, \var{Nil} if no ancestor available.\\
  3065. +12 & Pointer to the class name (stored as a \var{shortstring}). \\
  3066. +16 & Pointer to the dynamic method table (using \var{message} with integers).\\
  3067. +20 & Pointer to the method definition table. \\
  3068. +24 & Pointer to the field definition table. \\
  3069. +28 & Pointer to type information table. \\
  3070. +32 & Pointer to instance initialization table. \\
  3071. +36 & Reserved.\\
  3072. +40 & Pointer to the interface table. \\
  3073. +44 & Pointer to the dynamic method table (using \var{message} with strings).\\
  3074. +48 & Pointer to the \var{Destroy} destructor. \\
  3075. +52 & Pointer to the \var{NewInstance} method. \\
  3076. +56 & Pointer to the \var{FreeInstance} method. \\
  3077. +60 & Pointer to the \var{SafeCallException} method. \\
  3078. +64 & Pointer to the \var{DefaultHandler} method. \\
  3079. +68 & Pointer to the \var{AfterConstruction} method. \\
  3080. +72 & Pointer to the \var{BeforeDestruction} method. \\
  3081. +76 & Pointer to the \var{DefaultHandlerStr} method. \\
  3082. +80 & Pointers to other virtual methods. \\
  3083. \dots & \\
  3084. \hline
  3085. \end{FPCltable}
  3086. \subsection{file types}
  3087. File types are represented as records. Typed files and untyped
  3088. files are represented as a fixed record:
  3089. \begin{verbatim}
  3090. filerec = packed record
  3091. handle : longint;
  3092. mode : longint;
  3093. recsize : longint;
  3094. _private : array[1..32] of byte;
  3095. userdata : array[1..16] of byte;
  3096. name : array[0..255] of char;
  3097. End;
  3098. \end{verbatim}
  3099. Text files are described using the following record:
  3100. \begin{verbatim}
  3101. TextBuf = array[0..255] of char;
  3102. textrec = packed record
  3103. handle : longint;
  3104. mode : longint;
  3105. bufsize : longint;
  3106. _private : longint;
  3107. bufpos : longint;
  3108. bufend : longint;
  3109. bufptr : ^textbuf;
  3110. openfunc : pointer;
  3111. inoutfunc : pointer;
  3112. flushfunc : pointer;
  3113. closefunc : pointer;
  3114. userdata : array[1..16] of byte;
  3115. name : array[0..255] of char;
  3116. buffer : textbuf;
  3117. End;
  3118. \end{verbatim}
  3119. \begin{description}
  3120. \item[handle] The handle field returns the file handle (if the file is
  3121. opened), as returned by the operating system.
  3122. \item[mode] The mode field can take one of several values. When it is
  3123. \var{fmclosed}, then the file is closed, and the \var{handle} field is invalid.
  3124. When the value is equal to \var{fminput}, it indicates that the file is
  3125. opened for read only access. \var{fmoutput} indicates write only access,
  3126. and the \var{fminout} indicates read-write access to the file.
  3127. \item[name] The \var{name} field is a null terminated character string representing
  3128. the name of the file.
  3129. \item[userdata] The \var{userdata} field is never used by \fpc, and can
  3130. be used for special purposes by software developpers.
  3131. \end{description}
  3132. \subsection{procedural types}
  3133. A procedural type to a normal procedure or function is stored as a generic pointer,
  3134. which stores the address of the entry point of the routine.
  3135. In the case of a method procedural type, the storage consists of two pointers,
  3136. the first being a pointer to the entry point of the method, and the second
  3137. one being a pointer to \var{self} (the object instance).
  3138. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3139. % The alignment of data elements
  3140. \section{Data alignment}
  3141. \label{se:Alignment}
  3142. \subsection{Typed constants and variable alignment}
  3143. All static data (variables and typed constants) which are greater than
  3144. a byte are usually aligned on a power of two boundary. This alignment
  3145. applies only to the start address of the variables, and not the alignment
  3146. of fields within structures or objects for example. For more information
  3147. on structured alignment, \sees{StructuredAlignment}. The alignment
  3148. is similar across the different target processors. \footnote{The Intel
  3149. 80x86 version does not align data in the case of constant strings,
  3150. constant sets, constant floating point values amd global variables.
  3151. This will be fixed in the version 1.1 release.}
  3152. \begin{FPCltable}{lccc}{Data alignment}{DataAlignment}
  3153. \hline
  3154. Data size (bytes) & Alignment (small size) & Alignment (fast)\\
  3155. 1 & 1 & 1\\
  3156. 2-3 & 2 & 2\\
  3157. 4-7 & 2 & 4\\
  3158. 8+ & 2 & 4\\
  3159. \hline
  3160. \end{FPCltable}
  3161. The alignment columns indicates the address alignment of the variable,
  3162. i.e the start address of the variable will be aligned on that boundary.
  3163. The small size alignment is valid when the code generated should be
  3164. optimized for size (\var{-Og} compiler option) and not speed, otherwise and
  3165. by default, the fast alignment is used to align the data.
  3166. \subsection{Structured types alignment}
  3167. \label{se:StructuredAlignment}
  3168. By default all elements in a structure are aligned to a 2 byte boundary,
  3169. unless the {\var{\$PACKRECORDS} directive or \var{packed} modifier is used
  3170. to align the data in another way. For example a \var{record} or \var{object}
  3171. having a 1 byte element, will have its size rounded up to 2, so the size of
  3172. the structure will actually be 2 bytes.
  3173. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3174. % The heap
  3175. \section{The heap}
  3176. \label{se:Heap}
  3177. The heap is used to store all dynamic variables, and to store class
  3178. instances. The interface to the heap is the same as in Turbo Pascal,
  3179. although the effects are maybe not the same. On top of that, the \fpc
  3180. run-time library has some extra possibilities, not available in Turbo
  3181. Pascal. These extra possibilities are explained in the next subsections.
  3182. % The heap algorithm
  3183. \subsection{Heap allocation strategy}
  3184. The heap is a memory structure which is organized as a stack. The heap
  3185. bottom is stored in the variable \var{HeapOrg}. Initially the heap
  3186. pointer (\var{HeapPtr}) points to the bottom of the heap. When a
  3187. variable is allocated on the heap, \var{HeapPtr} is incremented by the
  3188. size of the allocated memory block. This has the effect of stacking
  3189. dynamic variables on top of each other.
  3190. Each time a block is allocated, its size is normalized to have
  3191. a granularity of 16 bytes.
  3192. When \var{Dispose} or \var{FreeMem} is called to dispose of a
  3193. memory block which is not on the top of the heap, the heap becomes
  3194. fragmented. The deallocation routines also add the freed blocks to
  3195. the \var{freelist} which is actually a linked list of free blocks.
  3196. Furthermore, if the deallocated block was less then 8K in size, the
  3197. free list cache is also updated.
  3198. The free list cache is actually a cache of free heap blocks which
  3199. have specific lengths (the adjusted block size divided by 16 gives the
  3200. index into the free list cache table). It is faster to access then
  3201. searching through the entire \var{freelist}.
  3202. The format of an entry in the \var{freelist} is as follows:
  3203. \begin{verbatim}
  3204. PFreeRecord = ^TFreeRecord;
  3205. TFreeRecord = record
  3206. Size : longint;
  3207. Next : PFreeRecord;
  3208. Prev : PFreeRecord;
  3209. end;
  3210. \end{verbatim}
  3211. The \var{Next} field points to the next free block, while
  3212. the \var{Prev} field points to the previous free block.
  3213. The algorithm for allocating memory is as follows:
  3214. \begin{enumerate}
  3215. \item The size of the block to allocate is adjusted to a 16 byte granularity.
  3216. \item The cached free list is searched to find a free block of the specified
  3217. size or bigger size, if so it is allocated and the routine exits.
  3218. \item The \var{freelist} is searched to find a free block of the specified size
  3219. or of bigger size, if so it is allocated and the routine exits.
  3220. \item If not found in the \var{freelist} the heap is grown to allocate the
  3221. specified memory, and the routine exits.
  3222. \item If the heap cannot be grown internally anymore and if \var{heaperror} is set
  3223. accordingly, it calls the heap error handler. If there is no heap error handler
  3224. installed, the runtime library generates a runtime error 203.
  3225. \end{enumerate}
  3226. % Error handler routinr
  3227. \subsection{The HeapError variable}
  3228. The heap error permits developpers to install a heap error hook which
  3229. is called each time an allocation cannot be completed by the default
  3230. heap manager. \var{HeapError} is a pointer that points to a function
  3231. with the following prototype:
  3232. \begin{verbatim}
  3233. function HeapFunc(size : longint): integer;
  3234. \end{verbatim}
  3235. The \var{size} parameter indicates the size of the block which could
  3236. not be allocated. Depending on the success, the error handler routine
  3237. should return a value which indicates what the default heap manager
  3238. should do thereafter (cf. \seet{Heaperrorresult}).
  3239. \begin{FPCltable}{|c|l|}{Heap error result}{Heaperrorresult}
  3240. \hline
  3241. Value returned & Memory manager action \\
  3242. \hline
  3243. 0 & Generates a runtime error 203 \\
  3244. 1 & \var{GetMem},\var{ReallocMem} and \var{New} returns \var{nil} \\
  3245. 2 & Try allocating the memory block once again \\
  3246. \hline
  3247. \end{FPCltable}
  3248. % The heap grows
  3249. \subsection{The heap grows}
  3250. By default, \var{HeapError} points to the \var{GrowHeap} function,
  3251. which tries to increase the heap.
  3252. The \var{GrowHeap} function issues a system call to try to increase the size of the
  3253. memory available to your program. It first tries to increase memory in a 256Kb
  3254. chunk if the size to allocate is less than 256Kb, or 1024K otherwise.
  3255. If this fails, it tries to increase the heap by the amount you requested
  3256. from the heap.
  3257. If the call to \var{GrowHeap} was successful, then the needed memory will be
  3258. allocated.
  3259. If the call to \var{GrowHeap} fails, the value returned depends on the
  3260. value of the \var{ReturnNilIfGrowHeapFails} global variable. This is summarized
  3261. in \seet{growheapnil}.
  3262. \begin{FPCltable}{|c|l|}{ReturnNilIfGrowHeapFails value}{growheapnil}
  3263. \hline
  3264. ReturnNilGrowHeapFails & Default memory \\
  3265. value & manager action \\
  3266. \hline
  3267. FALSE & (The default) Runtime error 203 generated \\
  3268. TRUE & \var{GetMem}, \var{ReallocMem} and \var{New} returns \var{nil} \\
  3269. \hline
  3270. \end{FPCltable}
  3271. \var{ReturnNilIfGrowHeapFails} can be set to change the behavior of
  3272. the default memory manager error handler.
  3273. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3274. % Debugging the heap
  3275. \subsection{Debugging the heap}
  3276. \fpc provides a unit that allows you to trace allocation and deallocation
  3277. of heap memory: \file{heaptrc}.
  3278. If you specify the \var{-gh} switch on the command-line, or if you include
  3279. \var{heaptrc} as the first unit in your uses clause, the memory manager
  3280. will trace what is allocated and deallocated, and on exit of your program,
  3281. a summary will be sent to standard output.
  3282. More information on using the \var{heaptrc} mechanism can be found in the
  3283. \userref and \unitsref.
  3284. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3285. % Writing your own memory manager.
  3286. \subsection{Writing your own memory manager}
  3287. \fpc allows you to write and use your own memory manager. The standard
  3288. functions \var{GetMem}, \var{FreeMem}, \var{ReallocMem} and \var{Maxavail}
  3289. use a special record in the \file{system} unit to do the actual memory management.
  3290. The \file{system} unit initializes this record with the \file{system} unit's own memory
  3291. manager, but you can read and set this record using the
  3292. \var{GetMemoryManager} and \var{SetMemoryManager} calls:
  3293. \begin{verbatim}
  3294. procedure GetMemoryManager(var MemMgr: TMemoryManager);
  3295. procedure SetMemoryManager(const MemMgr: TMemoryManager);
  3296. \end{verbatim}
  3297. the \var{TMemoryManager} record is defined as follows:
  3298. \begin{verbatim}
  3299. TMemoryManager = record
  3300. Getmem : Function(Size:Longint):Pointer;
  3301. Freemem : Function(var p:pointer):Longint;
  3302. FreememSize : Function(var p:pointer;Size:Longint):Longint;
  3303. AllocMem : Function(Size:longint):Pointer;
  3304. ReAllocMem : Function(var p:pointer;Size:longint):Pointer;
  3305. MemSize : function(p:pointer):Longint;
  3306. MemAvail : Function:Longint;
  3307. MaxAvail : Function:Longint;
  3308. HeapSize : Function:Longint;
  3309. end;
  3310. \end{verbatim}
  3311. As you can see, the elements of this record are procedural variables.
  3312. The \file{system} unit does nothing but call these various variables when you
  3313. allocate or deallocate memory.
  3314. Each of these functions corresponds to the corresponding call in the \file{system}
  3315. unit. We'll describe each one of them:
  3316. \begin{description}
  3317. \item[Getmem] This function allocates a new block on the heap. The block
  3318. should be \var{Size} bytes long. The return value is a pointer to the newly
  3319. allocated block.
  3320. \item[Freemem] should release a previously allocated block. The pointer
  3321. \var{P} points to a previously allocated block. The Memory manager should
  3322. implement a mechanism to determine what the size of the memory block is
  3323. \footnote{By storing it's size at a negative offset for instance.} The
  3324. return value is optional, and can be used to return the size of the freed
  3325. memory.
  3326. \item[FreememSize] This function should release the memory pointed to by
  3327. \var{P}. The argument \var{Size} is the expected size of the memory block
  3328. pointed to by P. This should be disregarded, but can be used to check the
  3329. behaviour of the program.
  3330. \item[AllocMem] Is the same as getmem, only the allocated memory should
  3331. be filled with zeroes before the call returns.
  3332. \item[ReAllocMem] Should allocate a memory block \var{Size} bytes large,
  3333. and should fill it with the contents of the memory block pointed to by
  3334. \var{P}, truncating this to the new size of needed. After that, the memory
  3335. pointed to by P may be deallocated. The return value is a pointer to the
  3336. new memory block.
  3337. \item[MemSize] should return the total amount of memory available for
  3338. allocation. This function may return zero if the memory manager does not
  3339. allow to determine this information.
  3340. \item[MaxAvail] should return the size of the largest block of memory that
  3341. is still available for allocation. This function may return zero if the
  3342. memory manager does not allow to determine this information.
  3343. \item[HeapSize] should return the total size of the heap. This may be zero
  3344. is the memory manager does not allow to determine this information.
  3345. \end{description}
  3346. To implement your own memory manager, it is sufficient to construct such a
  3347. record and to issue a call to \var{SetMemoryManager}.
  3348. To avoid conflicts with the system memory manager, setting the memory
  3349. manager should happen as soon as possible in the initialization of your
  3350. program, i.e. before any call to \var{getmem} is processed.
  3351. This means in practice that the unit implementing the memory manager should
  3352. be the first in the \var{uses} clause of your program or library, since it
  3353. will then be initialized before all other units (except of the \file{system} unit)
  3354. This also means that it is not possible to use the \file{heaptrc} unit in
  3355. combination with a custom memory manager, since the \file{heaptrc} unit uses
  3356. the system memory manager to do all it's allocation. Putting the
  3357. \file{heaptrc} unit after the unit implementing the memory manager would
  3358. overwrite the memory manager record installed by the custom memory manager,
  3359. and vice versa.
  3360. The following unit shows a straightforward implementation of a custom
  3361. memory manager using the memory manager of the \var{C} library. It is
  3362. distributed as a package with \fpc.
  3363. \begin{verbatim}
  3364. unit cmem;
  3365. {$mode objfpc}
  3366. interface
  3367. Function Malloc (Size : Longint) : Pointer;cdecl;
  3368. external 'c' name 'malloc';
  3369. Procedure Free (P : pointer); cdecl; external 'c' name 'free';
  3370. Procedure FreeMem (P : Pointer); cdecl; external 'c' name 'free';
  3371. function ReAlloc (P : Pointer; Size : longint) : pointer; cdecl;
  3372. external 'c' name 'realloc';
  3373. Function CAlloc (unitSize,UnitCount : Longint) : pointer;cdecl;
  3374. external 'c' name 'calloc';
  3375. implementation
  3376. Function CGetMem (Size : Longint) : Pointer;
  3377. begin
  3378. result:=Malloc(Size);
  3379. end;
  3380. Function CFreeMem (Var P : pointer) : Longint;
  3381. begin
  3382. Free(P);
  3383. Result:=0;
  3384. end;
  3385. Function CFreeMemSize(var p:pointer;Size:Longint):Longint;
  3386. begin
  3387. Result:=CFreeMem(P);
  3388. end;
  3389. Function CAllocMem(Size : Longint) : Pointer;
  3390. begin
  3391. Result:=calloc(Size,1);
  3392. end;
  3393. Function CReAllocMem (var p:pointer;Size:longint):Pointer;
  3394. begin
  3395. Result:=realloc(p,size);
  3396. end;
  3397. Function CMemSize (p:pointer): Longint;
  3398. begin
  3399. Result:=0;
  3400. end;
  3401. Function CMemAvail : Longint;
  3402. begin
  3403. Result:=0;
  3404. end;
  3405. Function CMaxAvail: Longint;
  3406. begin
  3407. Result:=0;
  3408. end;
  3409. Function CHeapSize : Longint;
  3410. begin
  3411. Result:=0;
  3412. end;
  3413. Const
  3414. CMemoryManager : TMemoryManager =
  3415. (
  3416. GetMem : CGetmem;
  3417. FreeMem : CFreeMem;
  3418. FreememSize : CFreememSize;
  3419. AllocMem : CAllocMem;
  3420. ReallocMem : CReAllocMem;
  3421. MemSize : CMemSize;
  3422. MemAvail : CMemAvail;
  3423. MaxAvail : MaxAvail;
  3424. HeapSize : CHeapSize;
  3425. );
  3426. Var
  3427. OldMemoryManager : TMemoryManager;
  3428. Initialization
  3429. GetMemoryManager (OldMemoryManager);
  3430. SetMemoryManager (CmemoryManager);
  3431. Finalization
  3432. SetMemoryManager (OldMemoryManager);
  3433. end.
  3434. \end{verbatim}
  3435. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3436. % Accessing DOS memory under the GO32 extender
  3437. \section{Using \dos memory under the Go32 extender}
  3438. \label{se:AccessingDosMemory}
  3439. Because \fpc for \dos is a 32 bit compiler, and uses a \dos extender, accessing DOS
  3440. memory isn't trivial. What follows is an attempt to an explanation of how to
  3441. access and use \dos or real mode memory\footnote{Thanks for the explanation to
  3442. Thomas Schatzl (E-mail: \var{tom\_at\[email protected]})}.
  3443. In {\em Proteced Mode}, memory is accessed through {\em Selectors} and
  3444. {\em Offsets}. You can think of Selectors as the protected mode
  3445. equivalents of segments.
  3446. In \fpc, a pointer is an offset into the \var{DS} selector, which points to
  3447. the Data of your program.
  3448. To access the (real mode) \dos memory, somehow you need a selector that
  3449. points to the \dos memory.
  3450. The \file{go32} unit provides you with such a selector: The
  3451. \var{DosMemSelector} variable, as it is conveniently called.
  3452. You can also allocate memory in \dos's memory space, using the
  3453. \var{global\_dos\_alloc} function of the \file{go32} unit.
  3454. This function will allocate memory in a place where \dos sees it.
  3455. As an example, here is a function that returns memory in real mode \dos and
  3456. returns a selector:offset pair for it.
  3457. \begin{verbatim}
  3458. procedure dosalloc(var selector : word;
  3459. var segment : word;
  3460. size : longint);
  3461. var result : longint;
  3462. begin
  3463. result := global_dos_alloc(size);
  3464. selector := word(result);
  3465. segment := word(result shr 16);
  3466. end;
  3467. \end{verbatim}
  3468. (You need to free this memory using the \var{global\_dos\_free} function.)
  3469. You can access any place in memory using a selector. You can get a selector
  3470. using the \var{allocate\_ldt\_descriptor} function, and then let this selector
  3471. point to the physical memory you want using the
  3472. \var{set\_segment\_base\_address} function, and set its length using
  3473. \var{set\_segment\_limit} function.
  3474. You can manipulate the memory pointed to by the selector using the functions
  3475. of the GO32 unit. For instance with the \var{seg\_fillchar} function.
  3476. After using the selector, you must free it again using the
  3477. \var{free\_ldt\_selector} function.
  3478. More information on all this can be found in the \unitsref, the chapter on
  3479. the \file{go32} unit.
  3480. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3481. % Resource strings
  3482. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3483. \chapter{Resource strings}
  3484. \label{resourcestrings}
  3485. \section{Introduction}
  3486. Resource strings primarily exist to make internationalization of
  3487. applications easier, by introducing a language construct that provides
  3488. a uniform way of handling constant strings.
  3489. Most applications communicate with the user through some messages on the
  3490. graphical screen or console. Storing these messages in special constants
  3491. allows to store them in a uniform way in separate files, which can be used
  3492. for translation. A programmers interface exists to manipulate the actual
  3493. values of the constant strings at runtime, and a utility tool comes with the
  3494. Free Pascal compiler to convert the resource string files to whatever format
  3495. is wanted by the programmer. Both these things are discussed in the
  3496. following sections.
  3497. \section{The resource string file}
  3498. When a unit is compiled that contains a \var{resourcestring} section,
  3499. the compiler does 2 things:
  3500. \begin{enumerate}
  3501. \item It generates a table that contains the value of the strings as it
  3502. is declared in the sources.
  3503. \item It generates a {\em resource string file} that contains the names
  3504. of all strings, together with their declared values.
  3505. \end{enumerate}
  3506. This approach has 2 advantages: first of all, the value of the string is
  3507. always present in the program. If the programmer doesn't care to translate
  3508. the strings, the default values are always present in the binary. This also
  3509. avoids having to provide a file containing the strings. Secondly, having all
  3510. strings together in a compiler generated file ensures that all strings are
  3511. together (you can have multiple resourcestring sections in 1 unit or program)
  3512. and having this file in a fixed format, allows the programmer to choose his
  3513. way of internationalization.
  3514. For each unit that is compiled and that contains a resourcestring section,
  3515. the compiler generates a file that has the name of the unit, and an
  3516. extension \file{.rst}. The format of this file is as follows:
  3517. \begin{enumerate}
  3518. \item An empty line.
  3519. \item A line starting with a hash sign (\var{\#}) and the hash value of the
  3520. string, preceded by the text \var{hash value =}.
  3521. \item A third line, containing the name of the resource string in the format
  3522. \var{unitname.constantname}, all lowercase, followed by an equal sign, and
  3523. the string value, in a format equal to the pascal representation of this
  3524. string. The line may be continued on the next line, in that case it reads as
  3525. a pascal string expression with a plus sign in it.
  3526. \item Another empty line.
  3527. \end{enumerate}
  3528. If the unit contains no \var{resourcestring} section, no file is generated.
  3529. For example, the following unit:
  3530. \begin{verbatim}
  3531. unit rsdemo;
  3532. {$mode delphi}
  3533. {$H+}
  3534. interface
  3535. resourcestring
  3536. First = 'First';
  3537. Second = 'A Second very long string that should cover more than 1 line';
  3538. implementation
  3539. end.
  3540. \end{verbatim}
  3541. Will result in the following resource string file:
  3542. \begin{verbatim}
  3543. # hash value = 5048740
  3544. rsdemo.first='First'
  3545. # hash value = 171989989
  3546. rsdemo.second='A Second very long string that should cover more than 1 li'+
  3547. 'ne'
  3548. \end{verbatim}
  3549. The hash value is calculated with the function \var{Hash}. It is present in
  3550. the \file{objpas} unit. The value is the same value that the GNU gettext
  3551. mechanism uses. It is in no way unique, and can only be used to speed up
  3552. searches.
  3553. The \file{rstconv} utility that comes with the \fpc compiler allows to
  3554. manipulate these resource string files. At the moment, it can only be used
  3555. to make a \file{.po} file that can be fed to the GNU \file{msgfmt} program.
  3556. If someone wishes to have another format (Win32 resource files spring to
  3557. mind), one can enhance the \file{rstconv} program so it can generate
  3558. other types of files as well. GNU gettext was chosen because it is available
  3559. on all platforms, and is already widely used in the \var{Unix} and free
  3560. software community. Since the \fpc team doesn't want to restrict the use
  3561. of resource strings, the \file{.rst} format was chosen to provide a neutral
  3562. method, not restricted to any tool.
  3563. If you use resource strings in your units, and you want people to be able to
  3564. translate the strings, you must provide the resource string file. Currently,
  3565. there is no way to extract them from the unit file, though this is in
  3566. principle possible. It is not required to do this, the program can be
  3567. compiled without it, but then the translation of the strings isn't possible.
  3568. \section{Updating the string tables}
  3569. Having compiled a program with resourcestrings is not enough to
  3570. internationalize your program. At run-time, the program must initialize
  3571. the string tables with the correct values for the anguage that the user
  3572. selected. By default no such initialization is performed. All strings
  3573. are initialized with their declared values.
  3574. The \file{objpas} unit provides the mechanism to correctly initialize
  3575. the string tables. There is no need to include this unit in a \var{uses}
  3576. clause, since it is automatically loaded when a program or unit is
  3577. compiled in \var{Delphi} or \var{objfpc} mode. Since this is required
  3578. to use resource strings, the unit is always loaded when needed.
  3579. The resource strings are stored in tables, one per unit, and one for the
  3580. program, if it contains a \var{resourcestring} section as well. Each
  3581. resourcestring is stored with it's name, hash value, default value, and
  3582. the current value, all as \var{AnsiStrings}.
  3583. The objpas unit offers methods to retrieve the number of resourcestring
  3584. tables, the number of strings per table, and the above information for each
  3585. string. It also offers a method to set the current value of the strings.
  3586. Here are the declarations of all the functions:
  3587. \begin{verbatim}
  3588. Function ResourceStringTableCount : Longint;
  3589. Function ResourceStringCount(TableIndex : longint) : longint;
  3590. Function GetResourceStringName(TableIndex,
  3591. StringIndex : Longint) : Ansistring;
  3592. Function GetResourceStringHash(TableIndex,
  3593. StringIndex : Longint) : Longint;
  3594. Function GetResourceStringDefaultValue(TableIndex,
  3595. StringIndex : Longint) : AnsiString;
  3596. Function GetResourceStringCurrentValue(TableIndex,
  3597. StringIndex : Longint) : AnsiString;
  3598. Function SetResourceStringValue(TableIndex,
  3599. StringIndex : longint;
  3600. Value : Ansistring) : Boolean;
  3601. Procedure SetResourceStrings (SetFunction : TResourceIterator);
  3602. \end{verbatim}
  3603. Two other function exist, for convenience only:
  3604. \begin{verbatim}
  3605. Function Hash(S : AnsiString) : longint;
  3606. Procedure ResetResourceTables;
  3607. \end{verbatim}
  3608. Here is a short explanation of what each function does. A more detailed
  3609. explanation of the functions can be found in the \refref.
  3610. \begin{description}
  3611. \item[ResourceStringTableCount] returns the number of resource string tables
  3612. in the program.
  3613. \item[ResourceStringCount] returns the number of resource string entries in
  3614. a given table (tables are denoted by a zero-based index).
  3615. \item[GetResourceStringName] returns the name of a resource string in a
  3616. resource table. This is the name of the unit, a dot (.) and the name of
  3617. the string constant, all in lowercase. The strings are denoted by index,
  3618. also zero-based.
  3619. \item[GetResourceStringHash] returns the hash value of a resource string, as
  3620. calculated by the compiler with the \var{Hash} function.
  3621. \item[GetResourceStringDefaultValue] returns the default value of a resource
  3622. string, i.e. the value that appears in the resource string declaration, and
  3623. that is stored in the binary.
  3624. \item[GetResourceStringCurrentValue] returns the current value of a resource
  3625. string, i.e. the value set by the initialization (the default value), or the
  3626. value set by some previous internationalization routine.
  3627. \item[SetResourceStringValue] sets the current value of a resource string.
  3628. This function must be called to initialize all strings.
  3629. \item[SetResourceStrings] giving this function a callback will cause the
  3630. calback to be called for all resource strings, one by one, and set the value
  3631. of the string to the return value of the callback.
  3632. \end{description}
  3633. Two other functions exist, for convenience only:
  3634. \begin{description}
  3635. \item [Hash] can be used to calculate the hash value of a string. The hash
  3636. value stored in the tables is the result of this function, applied on the
  3637. default value. That value is calculated at compile time by the compiler.
  3638. \item[ResetResourceTables] will reset all the resource strings to their
  3639. default values. It is called by the initialization code of the objpas unit.
  3640. \end{description}
  3641. Given some \var{Translate} function, the following code would initialize
  3642. all resource strings:
  3643. \begin{verbatim}
  3644. Var I,J : Longint;
  3645. S : AnsiString;
  3646. begin
  3647. For I:=0 to ResourceStringTableCount-1 do
  3648. For J:=0 to ResourceStringCount(i)-1 do
  3649. begin
  3650. S:=Translate(GetResourceStringDefaultValue(I,J));
  3651. SetResourceStringValue(I,J,S);
  3652. end;
  3653. end;
  3654. \end{verbatim}
  3655. Other methods are of course possible, and the \var{Translate} function
  3656. can be implemented in a variety of ways.
  3657. \section{GNU gettext}
  3658. The unit \file{gettext} provides a way to internationalize an application
  3659. with the GNU \file{gettext} utilities. This unit is supplied with the
  3660. Free Component Library (FCL). it can be used as follows:
  3661. for a given application, the following steps must be followed:
  3662. \begin{enumerate}
  3663. \item Collect all resource string files and concatenate them together.
  3664. \item Invoke the \file{rstconv} program with the file resulting out of step
  3665. 1, resulting in a single \file{.po} file containing all resource strings of
  3666. the program.
  3667. \item Translate the \file{.po} file of step 2 in all required languages.
  3668. \item Run the \file{msgfmt} formatting program on all the \file{.po} files,
  3669. resulting in a set of \file{.mo} files, which can be distributed with your
  3670. application.
  3671. \item Call the \file{gettext} unit's \var{TranslateReosurceStrings} method,
  3672. giving it a template for the location of the \file{.mo} files, e.g. as in
  3673. \begin{verbatim}
  3674. TranslateResourcestrings('intl/restest.%s.mo');
  3675. \end{verbatim}
  3676. the \var{\%s} specifier will be replaced by the contents of the \var{LANG}
  3677. environment variable. This call should happen at program startup.
  3678. \end{enumerate}
  3679. An example program exists in the FCL sources, in the \file{fcl/tests}
  3680. directory.
  3681. \section{Caveat}
  3682. In principle it is possible to translate all resource strings at any time in
  3683. a running program. However, this change is not communicated to other
  3684. strings; its change is noticed only when a constant string is being used.
  3685. Consider the following example:
  3686. \begin{verbatim}
  3687. Const
  3688. help = 'With a little help of a programmer.';
  3689. Var
  3690. A : AnsiString;
  3691. begin
  3692. { lots of code }
  3693. A:=Help;
  3694. { Again some code}
  3695. TranslateStrings;
  3696. { More code }
  3697. \end{verbatim}
  3698. After the call to \var{TranslateStrings}, the value of \var{A} will remain
  3699. unchanged. This means that the assignment \var{A:=Help} must be executed
  3700. again in order for the change to become visible. This is important,
  3701. especially for GUI programs which have e.g. a menu. In order for the
  3702. change in resource strings to become visible, the new values must be
  3703. reloaded by program code into the menus \dots
  3704. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3705. % Optimizations done in the compiler
  3706. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3707. \chapter{Optimizations}
  3708. \section{Non processor specific}
  3709. The following sections describe the general optimizations
  3710. done by the compiler, they are not processor specific. Some
  3711. of these require some compiler switch override while others are done
  3712. automatically (those which require a switch will be noted as such).
  3713. \subsection{Constant folding}
  3714. In \fpc, if the operand(s) of an operator are constants, they
  3715. will be evaluated at compile time.
  3716. Example
  3717. \begin{verbatim}
  3718. x:=1+2+3+6+5;
  3719. \end{verbatim}
  3720. will generate the same code as
  3721. \begin{verbatim}
  3722. x:=17;
  3723. \end{verbatim}
  3724. Furthermore, if an array index is a constant, the offset will
  3725. be evaluated at compile time. This means that accessing MyData[5]
  3726. is as efficient as accessing a normal variable.
  3727. Finally, calling \var{Chr}, \var{Hi}, \var{Lo}, \var{Ord}, \var{Pred},
  3728. or \var{Succ} functions with constant parameters generates no
  3729. run-time library calls, instead, the values are evaluated at
  3730. compile time.
  3731. \subsection{Constant merging}
  3732. Using the same constant string, floating point value or constant set
  3733. two or more times generates only one copy of that constant.
  3734. \subsection{Short cut evaluation}
  3735. Evaluation of boolean expression stops as soon as the result is
  3736. known, which makes code execute faster then if all boolean operands
  3737. were evaluated.
  3738. \subsection{Constant set inlining}
  3739. Using the \var{in} operator is always more efficient then using the
  3740. equivalent \verb|<>|, \verb|=|, \verb|<=|, \verb|>=|, \verb|<| and \verb|>|
  3741. operators. This is because range comparisons can be done more easily with
  3742. \var{in} then with normal comparison operators.
  3743. \subsection{Small sets}
  3744. Sets which contain less then 33 elements can be directly encoded
  3745. using a 32-bit value, therefore no run-time library calls to
  3746. evaluate operands on these sets are required; they are directly encoded
  3747. by the code generator.
  3748. \subsection{Range checking}
  3749. Assignments of constants to variables are range checked at compile
  3750. time, which removes the need of the generation of runtime range checking
  3751. code.
  3752. \subsection{And instead of modulo}
  3753. When the second operand of a \var{mod} on an unsigned value is a constant
  3754. power of 2, an \var{and} instruction is used instead of an integer division.
  3755. This generates more efficient code.
  3756. \subsection{Shifts instead of multiply or divide}
  3757. When one of the operands in a multiplication is a power of
  3758. two, they are encoded using arithmetic shift instructions,
  3759. which generates more efficient code.
  3760. Similarly, if the divisor in a \var{div} operation is a power
  3761. of two, it is encoded using arithmetic shift instructions.
  3762. The same is true when accessing array indexes which are
  3763. powers of two, the address is calculated using arithmetic
  3764. shifts instead of the multiply instruction.
  3765. \subsection{Automatic alignment}
  3766. By default all variables larger then a byte are guaranteed to be aligned
  3767. at least on a word boundary.
  3768. Alignment on the stack and in the data section is processor dependant.
  3769. \subsection{Smart linking}
  3770. This feature removes all unreferenced code in the final executable
  3771. file, making the executable file much smaller.
  3772. Smart linking is switched on with the \var{-Cx} command-line switch, or
  3773. using the \var{\{\$SMARTLINK ON\}} global directive.
  3774. \subsection{Inline routines}
  3775. The following runtime library routines are coded directly into the
  3776. final executable: \var{Lo}, \var{Hi}, \var{High}, \var{Sizeof},
  3777. \var{TypeOf}, \var{Length}, \var{Pred}, \var{Succ}, \var{Inc},
  3778. \var{Dec} and \var{Assigned}.
  3779. \subsection{Stack frame omission}
  3780. Under specific conditions, the stack frame (entry and exit code for
  3781. the routine, see section \sees{CallingConventions}) will be omitted, and the
  3782. variable will directly be accessed via the stack pointer.
  3783. Conditions for omission of the stack frame:
  3784. \begin{itemize}
  3785. \item The function has no parameters nor local variables.
  3786. \item Routine is declared with the \var{assembler} modifier.
  3787. \item Routine is not a class.
  3788. \end{itemize}
  3789. \subsection{Register variables}
  3790. When using the \var{-Or} switch, local variables or parameters
  3791. which are used very often will be moved to registers for faster
  3792. access.
  3793. \section{Processor specific}
  3794. This lists the low-level optimizations performed, on a processor
  3795. per processor basis.
  3796. \subsection{Intel 80x86 specific}
  3797. Here follows a listing of the optimizing techniques used in the compiler:
  3798. \begin{enumerate}
  3799. \item When optimizing for a specific Processor (\var{-Op1, -Op2, -Op3},
  3800. the following is done:
  3801. \begin{itemize}
  3802. \item In \var{case} statements, a check is done whether a jump table
  3803. or a sequence of conditional jumps should be used for optimal performance.
  3804. \item Determines a number of strategies when doing peephole optimization, e.g.:
  3805. \var{movzbl (\%ebp), \%eax} will be changed into
  3806. \var{xorl \%eax,\%eax; movb (\%ebp),\%al } for Pentium and PentiumMMX.
  3807. \end{itemize}
  3808. \item When optimizing for speed (\var{-OG}, the default) or size (\var{-Og}), a choice is
  3809. made between using shorter instructions (for size) such as \var{enter \$4},
  3810. or longer instructions \var{subl \$4,\%esp} for speed. When smaller size is
  3811. requested, data is aligned to minimal boundaries. When speed is
  3812. requested, data is aligned on most efficient boundaries as much as possible.
  3813. \item Fast optimizations (\var{-O1}): activate the peephole optimizer
  3814. \item Slower optimizations (\var{-O2}): also activate the common subexpression
  3815. elimination (formerly called the "reloading optimizer")
  3816. \item Uncertain optimizations (\var{-Ou}): With this switch, the common subexpression
  3817. elimination algorithm can be forced into making uncertain optimizations.
  3818. Although you can enable uncertain optimizations in most cases, for people who
  3819. do not understand the following technical explanation, it might be the safest to
  3820. leave them off.
  3821. % Jonas's own words..
  3822. \begin{remark}If uncertain optimizations are enabled, the CSE algortihm assumes
  3823. that
  3824. \begin{itemize}
  3825. \item If something is written to a local/global register or a
  3826. procedure/function parameter, this value doesn't overwrite the value to
  3827. which a pointer points.
  3828. \item If something is written to memory pointed to by a pointer variable,
  3829. this value doesn't overwrite the value of a local/global variable or a
  3830. procedure/function parameter.
  3831. \end{itemize}
  3832. % end of quote
  3833. \end{remark}
  3834. The practical upshot of this is that you cannot use the uncertain
  3835. optimizations if you both write and read local or global variables directly and
  3836. through pointers (this includes \var{Var} parameters, as those are pointers too).
  3837. The following example will produce bad code when you switch on
  3838. uncertain optimizations:
  3839. \begin{verbatim}
  3840. Var temp: Longint;
  3841. Procedure Foo(Var Bar: Longint);
  3842. Begin
  3843. If (Bar = temp)
  3844. Then
  3845. Begin
  3846. Inc(Bar);
  3847. If (Bar <> temp) then Writeln('bug!')
  3848. End
  3849. End;
  3850. Begin
  3851. Foo(Temp);
  3852. End.
  3853. \end{verbatim}
  3854. The reason it produces bad code is because you access the global variable
  3855. \var{Temp} both through its name \var{Temp} and through a pointer, in this
  3856. case using the \var{Bar} variable parameter, which is nothing but a pointer
  3857. to \var{Temp} in the above code.
  3858. On the other hand, you can use the uncertain optimizations if
  3859. you access global/local variables or parameters through pointers,
  3860. and {\em only} access them through this pointer\footnote{
  3861. You can use multiple pointers to point to the same variable as well, that
  3862. doesn't matter.}.
  3863. For example:
  3864. \begin{verbatim}
  3865. Type TMyRec = Record
  3866. a, b: Longint;
  3867. End;
  3868. PMyRec = ^TMyRec;
  3869. TMyRecArray = Array [1..100000] of TMyRec;
  3870. PMyRecArray = ^TMyRecArray;
  3871. Var MyRecArrayPtr: PMyRecArray;
  3872. MyRecPtr: PMyRec;
  3873. Counter: Longint;
  3874. Begin
  3875. New(MyRecArrayPtr);
  3876. For Counter := 1 to 100000 Do
  3877. Begin
  3878. MyRecPtr := @MyRecArrayPtr^[Counter];
  3879. MyRecPtr^.a := Counter;
  3880. MyRecPtr^.b := Counter div 2;
  3881. End;
  3882. End.
  3883. \end{verbatim}
  3884. Will produce correct code, because the global variable \var{MyRecArrayPtr}
  3885. is not accessed directly, but only through a pointer (\var{MyRecPtr} in this
  3886. case).
  3887. In conclusion, one could say that you can use uncertain optimizations {\em
  3888. only} when you know what you're doing.
  3889. \end{enumerate}
  3890. \subsection{Motorola 680x0 specific}
  3891. Using the \var{-O2} switch does several optimizations in the
  3892. code produced, the most notable being:
  3893. \begin{itemize}
  3894. \item Sign extension from byte to long will use \var{EXTB}
  3895. \item Returning of functions will use \var{RTD}
  3896. \item Range checking will generate no run-time calls
  3897. \item Multiplication will use the long \var{MULS} instruction, no
  3898. runtime library call will be generated
  3899. \item Division will use the long \var{DIVS} instruction, no
  3900. runtime library call will be generated
  3901. \end{itemize}
  3902. \section{Optimization switches}
  3903. This is where the various optimizing switches and their actions are
  3904. described, grouped per switch.
  3905. \begin{description}
  3906. \item [-On:\ ] with n = 1..3: these switches activate the optimizer.
  3907. A higher level automatically includes all lower levels.
  3908. \begin{itemize}
  3909. \item Level 1 (\var{-O1}) activates the peephole optimizer
  3910. (common instruction sequences are replaced by faster equivalents).
  3911. \item Level 2 (\var{-O2}) enables the assembler data flow analyzer,
  3912. which allows the common subexpression elimination procedure to
  3913. remove unnecessary reloads of registers with values they already contain.
  3914. \item Level 3 (\var{-O3}) enables uncertain optimizations. For more info, see -Ou.
  3915. \end{itemize}
  3916. \item[-OG:\ ]
  3917. This causes the code generator (and optimizer, IF activated), to favor
  3918. faster, but code-wise larger, instruction sequences (such as
  3919. "\verb|subl $4,%esp|") instead of slower, smaller instructions
  3920. ("\verb|enter $4|"). This is the default setting.
  3921. \item[-Og:\ ] This one is exactly the reverse of -OG, and as such these
  3922. switches are mutually exclusive: enabling one will disable the other.
  3923. \item[-Or:\ ] This setting causes the code generator to
  3924. check which variables are used most, so it can keep those in a register.
  3925. \item[-Opn:\ ] with n = 1..3: Setting the target processor does NOT
  3926. activate the optimizer. It merely influences the code generator and,
  3927. if activated, the optimizer:
  3928. \begin{itemize}
  3929. \item During the code generation process, this setting is used to
  3930. decide whether a jump table or a sequence of successive jumps provides
  3931. the best performance in a case statement.
  3932. \item The peephole optimizer takes a number of decisions based on this
  3933. setting, for example it translates certain complex instructions, such
  3934. as
  3935. \begin{verbatim}
  3936. movzbl (mem), %eax|
  3937. \end{verbatim}
  3938. to a combination of simpler instructions
  3939. \begin{verbatim}
  3940. xorl %eax, %eax
  3941. movb (mem), %al
  3942. \end{verbatim}
  3943. for the Pentium.
  3944. \end{itemize}
  3945. \item[-Ou:\ ] This enables uncertain optimizations. You cannot use these
  3946. always, however. The previous section explains when they can be used, and
  3947. when they cannot be used.
  3948. \end{description}
  3949. \section{Tips to get faster code}
  3950. Here, some general tips for getting better code are presented. They
  3951. mainly concern coding style.
  3952. \begin{itemize}
  3953. \item Find a better algorithm. No matter how much you and the compiler
  3954. tweak the code, a quicksort will (almost) always outperform a bubble
  3955. sort, for example.
  3956. \item Use variables of the native size of the processor you're writing
  3957. for. This is currently 32-bit or 64-bit for \fpc, so you are best to
  3958. use longword and longint variables.
  3959. \item Turn on the optimizer.
  3960. \item Write your if/then/else statements so that the code in the "then"-part
  3961. gets executed most of the time (improves the rate of successful jump prediction).
  3962. \item Do not use ansistrings, widestrings and exception support, as these
  3963. require a lot of code overhead.
  3964. \item Profile your code (see the -pg switch) to find out where the
  3965. bottlenecks are. If you want, you can rewrite those parts in assembler.
  3966. You can take the code generated by the compiler as a starting point. When
  3967. given the \var{-a} command-line switch, the compiler will not erase the
  3968. assembler file at the end of the assembly process, so you can study the
  3969. assembler file.
  3970. \end{itemize}
  3971. \section{Tips to get smaller code}
  3972. Here are some tips given to get the smallest code possible.
  3973. \begin{itemize}
  3974. \item Find a better algorithm.
  3975. \item Use the \var{-Og} compiler switch.
  3976. \item Regroup global static variables in the same module which have the same
  3977. size together to minimize the number of alignment directives (which increases
  3978. the \var{.bss} and \var{.data} sections unecessarily). Internally this is
  3979. due to the fact that all static data is written to in the assembler file,
  3980. in the order they are declared in the pascal source code.
  3981. \item Do not use the \var{cdecl} modifier, as this generates
  3982. about 1 additional instruction after each subroutine call.
  3983. \item Use the smartlinking options for all your units
  3984. (including the \var{system} unit).
  3985. \item Do not use ansistrings, widestrings and exception support, as these
  3986. require a lot of code overhead.
  3987. \item Turn off range checking and stack-checking.
  3988. \item Turn off runtime type information generation
  3989. \end{itemize}
  3990. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3991. % programming shared libraries
  3992. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3993. \chapter{Programming shared libraries}
  3994. \label{ch:libraries}
  3995. \section{Introduction}
  3996. \fpc supports the creation of shared libraries on several operating
  3997. systems. The following table (\seet{DLLSupport}) indicates which
  3998. operating systems support the creation of shared libraries.
  3999. \begin{FPCltable}{lll}{Shared library support}{DLLSupport} \hline
  4000. Operating systems & Library extension & Library prefix \\ \hline
  4001. linux & .so & lib \\
  4002. windows & .dll & <none> \\
  4003. BeOS & .so & lib \\
  4004. FreeBSD & .so & lib \\
  4005. NetBSD & .so & lib \\
  4006. \hline
  4007. \end{FPCltable}
  4008. The library prefix column indicates how the names of the libraries are
  4009. resolved and created. For example, under \linux, the library name will
  4010. alwaus have the \var{lib} prefix when it is created. So if you create a
  4011. library called \file{mylib}, under \linux, this will result in the
  4012. \file{libmylib.so}. Furthermore, when importing routines from shared
  4013. libraries, it is not necessary to give the library prefix or the
  4014. filename extension.
  4015. In the following sections we discuss how to create a library, and how
  4016. to use these libraries in programs.
  4017. \section{Creating a library}
  4018. Creation of libraries is supported in any mode of the \fpc compiler,
  4019. but it may be that the arguments or return values differ if the library is
  4020. compiled in 2 different modes. E.g. if your function expects an
  4021. \var{Integer} argument, then the library will expect different integer
  4022. sizes if you compile it in Delphi mode or in TP mode.
  4023. A library can be created just as a program, only it uses the \var{library}
  4024. keyword, and it has an \var{exports} section. The following listing
  4025. demonstrates a simple library:
  4026. \FPCexample{subs}
  4027. The function \var{SubStr} does not have to be declared in the library file
  4028. itself. It can also be declared in the interface section of a unit that
  4029. is used by the library.
  4030. Compilation of this source will result in the creation of a library called
  4031. \file{libsubs.so} on \unix systems, or \file{subs.dll} on \windows or \ostwo.
  4032. The compiler will take care of any additional linking that is required to create a
  4033. shared library.
  4034. The library exports one function: \var{SubStr}. The case is important. The
  4035. case as it appears in the \var{exports} clause is used to export the
  4036. function.
  4037. If you want your library to be called from programs compiled with
  4038. other compilers, it is important to specify the correct calling
  4039. convention for the exported functions. Since the generated programs
  4040. by other compilers do not know about the \fpc calling conventions,
  4041. your functions would be called incorrectly, resulting in a corrupted
  4042. stack.
  4043. On \windows, most libraries use the \var{stdcall} convention, so it may be
  4044. better to use that one if your library is to be used on \windows systems. On
  4045. most \unix systems, the C calling convention is used, therefore the
  4046. \var{cdecl} modifier should be used in that case.
  4047. \section{Using a library in a pascal program}
  4048. In order to use a function that resides in a library, it is sufficient to
  4049. declare the function as it exists in the library as an \var{external}
  4050. function, with correct arguments and return type. The calling convention
  4051. used by the function should be declared correctly as well. The compiler
  4052. will then link the library as specified in the \var{external} statement
  4053. to your program\footnote{If you omit the library name in the \var{external}
  4054. modifier, then you can still tell the compiler to link to that library using
  4055. the \var{\{\$Linklib\}} directive.}.
  4056. For example, to use the library as defined above from a pascal program, you can use
  4057. the following pascal program:
  4058. \FPCexample{psubs}
  4059. As is shown in the example, you must declare the function as \var{external}.
  4060. Here also, it is necessary to specify the correct calling convention (it
  4061. should always match the convention as used by the function in the library),
  4062. and to use the correct casing for your declaration. Also notice, that
  4063. the library importing did not specify the filename extension, nor
  4064. was the \var{lib} prefix added.
  4065. This program can be compiled without any additional command-switches,
  4066. and should run just like that, provided the library is placed where
  4067. the system can find it. For example, on \linux, this is \file{/usr/lib} or any
  4068. directory listed in the \file{/etc/ld.so.conf} file. On \windows, this
  4069. can be the program directory, the \windows system directory, or any directoy
  4070. mentioned in the \var{PATH}.
  4071. Using the library in this way links the library to your program at compile
  4072. time. This means that
  4073. \begin{enumerate}
  4074. \item The library must be present on the system where the program is
  4075. compiled.
  4076. \item The library must be present on the system where the program is
  4077. executed.
  4078. \item Both libraries must be exactly the same.
  4079. \end{enumerate}
  4080. Or it may simply be that you don't know the name of the function to
  4081. be called, you just know the arguments it expects.
  4082. It is therefore also possible to load the library at run-time, store
  4083. the function address in a procedural variable, and use this procedural
  4084. variable to access the function in the library.
  4085. The following example demonstrates this technique:
  4086. \FPCexample{plsubs}
  4087. As in the case of compile-time linking, the crucial thing in this
  4088. listing is the declaration of the \var{TSubStrFunc} type.
  4089. It should match the declaration of the function you're trying to use.
  4090. Failure to specify a correct definition will result in a faulty stack or,
  4091. worse still, may cause your program to crash with an access violation.
  4092. \section{Using a pascal library from a C program}
  4093. \begin{remark}The examples in this section assume a \linux system; similar commands
  4094. as the ones below exist for other operating systems, though.
  4095. \end{remark}
  4096. You can also call a \fpc generated library from a C program:
  4097. \Cexample{ctest}
  4098. To compile this example, the following command can be used:
  4099. \begin{verbatim}
  4100. gcc -o ctest ctest.c -lsubs
  4101. \end{verbatim}
  4102. provided the code is in \file{ctest.c}.
  4103. The library can also be loaded dynamically from C, as shown in the following
  4104. example:
  4105. \Cexample{ctest2}
  4106. This can be compiled using the following command:
  4107. \begin{verbatim}
  4108. gcc -o ctest2 ctest2.c -ldl
  4109. \end{verbatim}
  4110. \lstset{language=delphi}
  4111. The \var{-ldl} tells gcc that the program needs the \file{libdl.so} library
  4112. to load dynamical libraries.
  4113. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4114. % using resources
  4115. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4116. \chapter{Using Windows resources}
  4117. \label{ch:windres}
  4118. \section{The resource directive \var{\$R}}
  4119. Under \windows, you can include resources in your executable or library
  4120. using the \var{\{\$R filename\}} directive. These resources can then
  4121. be accessed through the standard \windows API calls.
  4122. When the compiler encounters a resource directive, it just creates an
  4123. entry in the unit \file{.ppu} file; it doesn't link the resource. Only
  4124. when it creates a library or executable, it looks for all the resource
  4125. files for which it encountered a directive, and tries to link them in.
  4126. The default extension for resource files is \file{.res}. When the
  4127. filename has as the first character an asterix (\var{*}), the
  4128. compiler will replace the asterix with the name of the current unit,
  4129. library or program.
  4130. \begin{remark}This means that the asterix may only be used after a \var{unit},
  4131. \var{library} or \var{program} clause.
  4132. \end{remark}
  4133. \section{Creating resources}
  4134. The \fpc compiler itself doesn't create any resource files; it just
  4135. compiles them into the executable. To create resource files, you
  4136. can use some GUI tools as the Borland resource workshop; but it is
  4137. also possible to use a \windows resource compiler like \gnu
  4138. \file{windres}. \file{windres} comes with the \gnu binutils, but the
  4139. \fpc distribution also contains a version which you can use.
  4140. The usage of windres is straightforward; it reads an input file
  4141. describing the resources to create and outputs a resource file.
  4142. A typical invocation of \file{windres} would be
  4143. \begin{verbatim}
  4144. windres -i mystrings.rc -o mystrings.res
  4145. \end{verbatim}
  4146. this will read the \file{mystrings.rc} file and output a
  4147. \file{mystrings.res} resource file.
  4148. A complete overview of the windres tools is outside the scope of this
  4149. document, but here are some things you can use it for:
  4150. \begin{description}
  4151. \item[stringtables] that contain lists of strings.
  4152. \item[bitmaps] which are read from an external file.
  4153. \item[icons] which are also read from an external file.
  4154. \item[Version information] which can be viewed with the \windows
  4155. explorer.
  4156. \item[Menus] Can be designed as resources and used in your GUI
  4157. applications.
  4158. \item[Arbitrary data] Can be included as resources and read with the
  4159. windows API calls.
  4160. \end{description}
  4161. Some of these will be described below.
  4162. \section{Using string tables.}
  4163. String tables can be used to store and retrieve large collections of
  4164. strings in your application.
  4165. A string table looks as follows:
  4166. \begin{verbatim}
  4167. STRINGTABLE { 1, "hello World !"
  4168. 2, "hello world again !"
  4169. 3, "last hello world !" }
  4170. \end{verbatim}
  4171. You can compile this (we assume the file is called \file{tests.rc}) as
  4172. follows:
  4173. \begin{verbatim}
  4174. windres -i tests.rc -o tests.res
  4175. \end{verbatim}
  4176. And this is the way to retrieve the strings from your program:
  4177. \begin{verbatim}
  4178. program tests;
  4179. {$mode objfpc}
  4180. Uses Windows;
  4181. {$R *.res}
  4182. Function LoadResourceString (Index : longint): Shortstring;
  4183. begin
  4184. SetLength(Result,LoadString(FindResource(0,Nil,RT_STRING),Index,@Result[1],SizeOf(Result)))
  4185. end;
  4186. Var
  4187. I: longint;
  4188. begin
  4189. For i:=1 to 3 do
  4190. Writeln (Loadresourcestring(I));
  4191. end.
  4192. \end{verbatim}
  4193. The call to \var{FindResource} searches for the stringtable in the
  4194. compiled-in resources. The \var{LoadString} function then reads the
  4195. string with index \var{i} out of the table, and puts it in a buffer,
  4196. which can then be used. Both calls are in the \file{windows} unit.
  4197. \section{Inserting version information}
  4198. The win32 API allows to store version information in your binaries.
  4199. This information can be made visible with the \windows Explorer, by
  4200. right-clicking on the executable or library, and selecting the
  4201. 'Properties' menu. In the tab 'Version' the version information will
  4202. be displayed.
  4203. Here is how to insert version information in your binary:
  4204. \begin{verbatim}
  4205. 1 VERSIONINFO
  4206. FILEVERSION 4, 0, 3, 17
  4207. PRODUCTVERSION 3, 0, 0, 0
  4208. FILEFLAGSMASK 0
  4209. FILEOS 0x40000
  4210. FILETYPE 1
  4211. {
  4212. BLOCK "StringFileInfo"
  4213. {
  4214. BLOCK "040904E4"
  4215. {
  4216. VALUE "CompanyName", "Free Pascal"
  4217. VALUE "FileDescription", "Free Pascal version information extractor"
  4218. VALUE "FileVersion", "1.0"
  4219. VALUE "InternalName", "Showver"
  4220. VALUE "LegalCopyright", "GNU Public License"
  4221. VALUE "OriginalFilename", "showver.pp"
  4222. VALUE "ProductName", "Free Pascal"
  4223. VALUE "ProductVersion", "1.0"
  4224. }
  4225. }
  4226. }
  4227. \end{verbatim}
  4228. As you can see, you can insert various kinds of information in the version info
  4229. block. The keyword \var{VERSIONINFO} marks the beginning of the version
  4230. information resource block. The keywords \var{FILEVERSION},
  4231. \var{PRODUCTVERSION} give the actual file version, while the block
  4232. \var{StringFileInfo} gives other information that is displayed in the
  4233. explorer.
  4234. The Free Component Library comes with a unit (\file{fileinfo}) that allows
  4235. to extract and view version information in a straightforward and easy manner;
  4236. the demo program that comes with it (\file{showver}) shows version information
  4237. for an arbitrary executable or DLL.
  4238. \section{Inserting an application icon}
  4239. When \windows shows an executable in the Explorer, it looks for an icon
  4240. in the executable to show in front of the filename, the application
  4241. icon.
  4242. Inserting an application icon is very easy and can be done as follows
  4243. \begin{verbatim}
  4244. AppIcon ICON "filename.ico"
  4245. \end{verbatim}
  4246. This will read the file \file{filename.ico} and insert it in the
  4247. resource file.
  4248. \section{Using a pascal preprocessor}
  4249. Sometimes you want to use symbolic names in your resource file, and
  4250. use the same names in your program to access the resources. To accomplish
  4251. this, there exists a preprocessor for \file{windres} that understands pascal
  4252. syntax: \file{fprcp}. This preprocessor is shipped with the \fpc
  4253. distribution.
  4254. The idea is that the preprocessor reads a pascal unit that has some
  4255. symbolic constants defined in it, and replaces symbolic names in the
  4256. resource file by the values of the constants in the unit:
  4257. As an example: consider the follwoing unit:
  4258. \begin{verbatim}
  4259. unit myunit;
  4260. interface
  4261. Const
  4262. First = 1;
  4263. Second = 2:
  4264. Third = 3;
  4265. Implementation
  4266. end.
  4267. \end{verbatim}
  4268. And the following resource file:
  4269. \begin{verbatim}
  4270. #include "myunit.pp"
  4271. STRINGTABLE { First, "hello World !"
  4272. Second, "hello world again !"
  4273. Third, "last hello world !" }
  4274. \end{verbatim}
  4275. if you invoke windres with the \var{--preprocessor} option:
  4276. \begin{verbatim}
  4277. windres --preprocessor fprcp -i myunit.rc -o myunit.res
  4278. \end{verbatim}
  4279. Then the preprocessor will replace the symbolic names 'first', 'second'
  4280. and 'third' with their actual values.
  4281. In your program, you can then refer to the strings by their symbolic
  4282. names (the constants) instead of using a numeric index.
  4283. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4284. % Appendices
  4285. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4286. \appendix
  4287. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4288. % Appendix A
  4289. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4290. \chapter{Anatomy of a unit file}
  4291. \label{ch:AppA}
  4292. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4293. % Basics
  4294. \section{Basics}
  4295. As described in \seec{GenCode}, unit description files (hereafter
  4296. called PPU files for short), are used to determine if the unit
  4297. code must be recompiled or not. In other words, the PPU files act
  4298. as mini-makefiles, which is used to check dependencies of the
  4299. different code modules, as well as verify if the modules are up
  4300. to date or not. Furthermore, it contains all public symbols defined
  4301. for a module.
  4302. The general format of the \var{ppu} file format is shown
  4303. \begin{htmlonly}
  4304. here:
  4305. \fpcaddimg{../pics/ppu.png}
  4306. \end{htmlonly}
  4307. \begin{latexonly}
  4308. in \seefig{ppuformat}.
  4309. \begin{figure}
  4310. \caption{The PPU file format}
  4311. \label{fig:ppuformat}
  4312. \begin{center}
  4313. \ifpdf
  4314. \epsfig{file=pics/ppu.png}
  4315. \else
  4316. \epsfig{file=pics/ppu.eps}
  4317. \fi
  4318. \end{center}
  4319. \end{figure}
  4320. \end{latexonly}
  4321. To read or write the ppufile, the ppu unit \file{ppu.pas} can be used,
  4322. which has an object called tppufile which holds all routines that deal
  4323. with ppufile handling. While describing the layout of a ppufile, the
  4324. methods which can be used for it are presented as well.
  4325. A unit file consists of basically five or six parts:
  4326. \begin{enumerate}
  4327. \item A unit header.
  4328. \item A general information part (wrongly named interface section in the code)
  4329. \item A definition part. Contains all type and procedure definitions.
  4330. \item A symbol part. Contains all symbol names and references to their
  4331. definitions.
  4332. \item A browser part. Contains all references from this unit to other
  4333. units and inside this unit. Only available when the \var{uf\_has\_browser} flag is
  4334. set in the unit flags
  4335. \item A file implementation part (currently unused).
  4336. \end{enumerate}
  4337. \section{reading ppufiles}
  4338. We will first create an object ppufile which will be used below. We are
  4339. opening unit \file{test.ppu} as an example.
  4340. \begin{verbatim}
  4341. var
  4342. ppufile : pppufile;
  4343. begin
  4344. { Initialize object }
  4345. ppufile:=new(pppufile,init('test.ppu');
  4346. { open the unit and read the header, returns false when it fails }
  4347. if not ppufile.openfile then
  4348. error('error opening unit test.ppu');
  4349. { here we can read the unit }
  4350. { close unit }
  4351. ppufile.closefile;
  4352. { release object }
  4353. dispose(ppufile,done);
  4354. end;
  4355. \end{verbatim}
  4356. Note: When a function fails (for example not enough bytes left in an
  4357. entry) it sets the \var{ppufile.error} variable.
  4358. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4359. % The Header
  4360. \section{The Header}
  4361. The header consists of a record (\var{tppuheader}) containing
  4362. several pieces of information for recompilation. This is shown
  4363. in \seet{PPUHeader}. The header is always stored in little-endian
  4364. format.
  4365. \begin{FPCltable}{|l|c|l|}{PPU Header}{PPUHeader}
  4366. \hline
  4367. offset & size (bytes) & description \\
  4368. \hline
  4369. 00h & 3 & Magic : 'PPU' in ASCII \\
  4370. 03h & 3 & PPU File format version (e.g : '021' in ASCII) \\
  4371. 06h & 2 & Compiler version used to compile this module (major,minor)\\
  4372. 08h & 2 & Code module target processor \\
  4373. 0Ah & 2 & Code module target operating system \\
  4374. 0Ch & 4 & Flags for PPU file \\
  4375. 10h & 4 & Size of PPU file (without header) \\
  4376. 14h & 4 & CRC-32 of the entire PPU file \\
  4377. 18h & 4 & CRC-32 of partial data of PPU file (public data mostly) \\
  4378. 1Ch & 8 & Reserved \\
  4379. \hline
  4380. \end{FPCltable}
  4381. The header is already read by the \var{ppufile.openfile} command.
  4382. You can access all fields using \var{ppufile.header} which holds
  4383. the current header record.
  4384. \begin{FPCltable}{|ll|}{PPU CPU Field values}{PPUHeaderCPU}
  4385. \hline
  4386. value & description \\
  4387. \hline
  4388. 0 & unknown \\
  4389. 1 & Intel 80x86 or compatible \\
  4390. 2 & Motorola 680x0 or compatible \\
  4391. 3 & Alpha AXP or compatible \\
  4392. 4 & PowerPC or compatible \\
  4393. \hline
  4394. \end{FPCltable}
  4395. Some of the possible flags in the header, are described in \seet{PPUHeaderFlags}.
  4396. Not all the flags are described, for more information, read the source code of
  4397. \file{ppu.pas}.
  4398. \begin{FPCltable}{|ll|}{PPU Header Flag values}{PPUHeaderFlags}
  4399. \hline
  4400. Symbolic bit flag name & Description\\
  4401. \hline
  4402. uf\_init & Module has an initialization (either Delphi or TP style) section. \\
  4403. uf\_finalize & Module has a finalization section. \\
  4404. uf\_big\_endian & All the data stored in the chunks is in big-endian format.\\
  4405. uf\_has\_browser & Unit contains symbol browser information. \\
  4406. uf\_smart\_linked & The code module has been smartlinked.\\
  4407. uf\_static\_linked & The code is statically linked. \\
  4408. uf\_has\_resources & Unit has resource section. \\
  4409. \hline
  4410. \end{FPCltable}
  4411. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
  4412. % The sections
  4413. \section{The sections}
  4414. Apart from the header section, all the data in the PPU file is separated
  4415. into data blocks, which permit easily adding additional data blocks,
  4416. without compromising backward compatibility. This is similar to both
  4417. Electronic Arts IFF chunk format and Microsoft's RIFF chunk format.
  4418. Each 'chunk' (\var{tppuentry}) has the following format, and can be
  4419. nested:
  4420. \begin{FPCltable}{|l|c|l|}{chunk data format}{ChunkFormats}
  4421. \hline
  4422. offset & size (bytes) & description \\
  4423. \hline
  4424. 00h & 1 & Block type (nested (2) or main (1)) \\
  4425. 01h & 1 & Block identifier \\
  4426. 02h & 4 & Size of this data block \\
  4427. 06h+ & <variable> & Data for this block \\
  4428. \hline
  4429. \end{FPCltable}
  4430. Each main section chunk must end with an end chunk. Nested chunks
  4431. are used for record, class or object fields.
  4432. To read an entry you can simply call \var{ppufile.readentry:byte},
  4433. it returns the
  4434. \var{tppuentry.nr} field, which holds the type of the entry.
  4435. A common way how this works is (example is for the symbols):
  4436. \begin{verbatim}
  4437. repeat
  4438. b:=ppufile.readentry;
  4439. case b of
  4440. ib<etc> : begin
  4441. end;
  4442. ibendsyms : break;
  4443. end;
  4444. until false;
  4445. \end{verbatim}
  4446. The possible entry types are found in \file{ppu.pas}, but a short
  4447. description of the most common ones are shown in \seet{PPUEntryTypes}.
  4448. \begin{FPCltable}{|lll|}{Possible PPU Entry types}{PPUEntryTypes}
  4449. \hline
  4450. Symbolic name & Location & Description\\
  4451. \hline
  4452. ibmodulename & General & Name of this unit.\\
  4453. ibsourcefiles & General & Name of source files.\\
  4454. ibusedmacros & General & Name and state of macros used.\\
  4455. ibloadunit & General & Modules used by this units. \\
  4456. inlinkunitofiles & General & Object files associated with this unit. \\
  4457. iblinkunitstaticlibs & General & Static libraries associated with this unit. \\
  4458. iblinkunitsharedlibs & General & Shared libraries associated with this unit. \\
  4459. ibendinterface & General & End of General information section. \\
  4460. ibstartdefs & Interface & Start of definitions. \\
  4461. ibenddefs & Interface & End of definitions. \\
  4462. ibstartsyms & Interface & Start of symbol data. \\
  4463. ibendsyms & Interface & End of symbol data. \\
  4464. ibendimplementation & Implementation & End of implementation data. \\
  4465. ibendbrowser & Browser & End of browser section. \\
  4466. ibend & General & End of Unit file. \\
  4467. \hline
  4468. \end{FPCltable}
  4469. Then you can parse each entry type yourself. \var{ppufile.readentry} will take
  4470. care of skipping unread bytes in the entry and reads the next entry
  4471. correctly! A special function is \var{skipuntilentry(untilb:byte):boolean;}
  4472. which will read the ppufile until it finds entry \var{untilb} in the main
  4473. entries.
  4474. Parsing an entry can be done with \var{ppufile.getxxx} functions. The
  4475. available functions are:
  4476. \begin{verbatim}
  4477. procedure ppufile.getdata(var b;len:longint);
  4478. function getbyte:byte;
  4479. function getword:word;
  4480. function getlongint:longint;
  4481. function getreal:ppureal;
  4482. function getstring:string;
  4483. \end{verbatim}
  4484. To check if you're at the end of an entry you can use the following
  4485. function:
  4486. \begin{verbatim}
  4487. function EndOfEntry:boolean;
  4488. \end{verbatim}
  4489. {\em notes:}
  4490. \begin{enumerate}
  4491. \item \var{ppureal} is the best real that exists for the cpu where the
  4492. unit is created for. Currently it is \var{extended} for i386 and
  4493. \var{single} for m68k.
  4494. \item the \var{ibobjectdef} and \var{ibrecorddef} have stored a definition
  4495. and symbol section for themselves. So you'll need a recursive call. See
  4496. \file{ppudump.pp} for a correct implementation.
  4497. \end{enumerate}
  4498. A complete list of entries and what their fields contain can be found
  4499. in \file{ppudump.pp}.
  4500. \section{Creating ppufiles}
  4501. Creating a new ppufile works almost the same as reading one.
  4502. First you need to init the object and call create:
  4503. \begin{verbatim}
  4504. ppufile:=new(pppufile,init('output.ppu'));
  4505. ppufile.createfile;
  4506. \end{verbatim}
  4507. After that you can simply write all needed entries. You'll have to take
  4508. care that you write at least the basic entries for the sections:
  4509. \begin{verbatim}
  4510. ibendinterface
  4511. ibenddefs
  4512. ibendsyms
  4513. ibendbrowser (only when you've set uf_has_browser!)
  4514. ibendimplementation
  4515. ibend
  4516. \end{verbatim}
  4517. Writing an entry is a little different than reading it. You need to first
  4518. put everything in the entry with ppufile.putxxx:
  4519. \begin{verbatim}
  4520. procedure putdata(var b;len:longint);
  4521. procedure putbyte(b:byte);
  4522. procedure putword(w:word);
  4523. procedure putlongint(l:longint);
  4524. procedure putreal(d:ppureal);
  4525. procedure putstring(s:string);
  4526. \end{verbatim}
  4527. After putting all the things in the entry you need to call
  4528. \var{ppufile.writeentry(ibnr:byte)} where \var{ibnr} is the entry number
  4529. you're writing.
  4530. At the end of the file you need to call \var{ppufile.writeheader} to write the
  4531. new header to the file. This takes automatically care of the new size of the
  4532. ppufile. When that is also done you can call \var{ppufile.closefile} and dispose the
  4533. object.
  4534. Extra functions/variables available for writing are:
  4535. \begin{verbatim}
  4536. ppufile.NewHeader;
  4537. ppufile.NewEntry;
  4538. \end{verbatim}
  4539. This will give you a clean header or entry. Normally this is called
  4540. automatically in \var{ppufile.writeentry}, so there should be no need to
  4541. call these methods.
  4542. \begin{verbatim}
  4543. ppufile.flush;
  4544. \end{verbatim}
  4545. to flush the current buffers to the disk
  4546. \begin{verbatim}
  4547. ppufile.do_crc:boolean;
  4548. \end{verbatim}
  4549. set to false if you don't want that the crc is updated, this is necessary
  4550. if you write for example the browser data.
  4551. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4552. % Appendix B
  4553. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4554. \chapter{Compiler and RTL source tree structure}
  4555. \label{ch:AppB}
  4556. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4557. % The compiler source tree
  4558. \section{The compiler source tree}
  4559. All compiler source files are in several directories, normally the
  4560. non-processor specific parts are in \file{source/compiler}. Subdirectories
  4561. are present for each of the supported processors and target operating systems.
  4562. For more informations about the structure of the compiler have a look at the
  4563. Compiler Manual which contains also some informations about
  4564. compiler internals.
  4565. The \file{compiler} directory also contains a subdirectory \var{utils},
  4566. which contains mainly the utilities for creation and maintainance of the
  4567. message files.
  4568. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4569. % The RTL source tree
  4570. \section{The RTL source tree}
  4571. The RTL source tree is divided in many subdirectories, but is very
  4572. structured and easy to understand. It mainly consists of three parts:
  4573. \begin{enumerate}
  4574. \item A OS-dependent directory. This contains the files that are different for
  4575. each operating system. When compiling the RTL, you should do it here. The
  4576. following directories exist:
  4577. \begin{itemize}
  4578. \item \file{atari} for the \atari.
  4579. \item \file{amiga} for the \amiga.
  4580. \item \file{beos} for \beos. It has one subdirectory for each of the
  4581. supported processors.
  4582. \item \file{freebsd} for the \freebsd platform.
  4583. \item \file{go32v1} For \dos, using the GO32v1 extender. Not maintained any
  4584. more.
  4585. \item \file{go32v2} For \dos, using the GO32v2 extender.
  4586. \item \file{linux} for \linux platforms. It has one subdirectory for each of the supported
  4587. processors.
  4588. \item \file{netbsd} for \netbsd platforms. It has one subdirectory for each of the supported
  4589. processors.
  4590. \item \file{palmos} for the \palmos Dragonball processor based platform.
  4591. \item \file{os2} for \ostwo.
  4592. \item \file{sunos} for the \solaris platform. It has one subdirectory for each of the supported
  4593. processors.
  4594. \item \file{qnx} for the \qnx.
  4595. \item \file{win32} for Win32 platforms.
  4596. \item \file{posix} for posix interfaces (used for easier porting).
  4597. \item \file{unix} for unix common interfaces (used for easier porting).
  4598. \end{itemize}
  4599. \item A processor dependent directory. This contains files that are system
  4600. independent, but processor dependent. It contains mostly optimized routines
  4601. for a specific processor. The following directories exist:
  4602. \begin{itemize}
  4603. \item \file{i386} for the Intel 80x86 series of processors.
  4604. \item \file{m68k} for the Motorola 680x0 series of processors.
  4605. \end{itemize}
  4606. \item An OS-independent and Processor independent directory: \file{inc}. This
  4607. contains complete units, and include files containing interface parts of
  4608. units as well as generic versions of processor specific routines.
  4609. \end{enumerate}
  4610. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4611. % Appendix C
  4612. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4613. \chapter{Compiler limits}
  4614. \label{ch:AppC}
  4615. There are certain compiler limits inherent to the compiler:
  4616. \begin{enumerate}
  4617. \item Procedure or Function definitions can be nested to a level of 32.
  4618. \item Maximally 1024 units can be used in a program when using the compiler.
  4619. You can change this by redefining the \var{maxunits} constant in the compiler
  4620. source file.
  4621. \item Arrays are limited to 2 GBytes in size in the default processor mode.
  4622. \end{enumerate}
  4623. For processor specific compiler limitations refer to the Processor
  4624. Limitations section in this guide (\ref{se:ProcessorLimits}).
  4625. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4626. % Appendix D
  4627. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4628. \chapter{Compiler modes}
  4629. \label{ch:AppD}
  4630. Here we list the exact effect of the different compiler modes. They can be
  4631. set with the \var{\$Mode} switch, or by command line switches.
  4632. \section{FPC mode}
  4633. This mode is selected by the \var{{\$MODE FPC}} switch. On the command-line,
  4634. this means that you use none of the other compatibility mode switches.
  4635. It is the default mode of the compiler. This means essentially:
  4636. \begin{enumerate}
  4637. \item You must use the address operator to assign procedural variables.
  4638. \item A forward declaration must be repeated exactly the same by the
  4639. implementation of a function/procedure. In particular, you can not omit the
  4640. parameters when implementing the function or procedure.
  4641. \item Overloading of functions is allowed.
  4642. \item Nested comments are allowed.
  4643. \item The Objpas unit is NOT loaded.
  4644. \item You can use the cvar type.
  4645. \item PChars are converted to strings automatically.
  4646. \end{enumerate}
  4647. \section{TP mode}
  4648. This mode is selected by the \var{{\$MODE TP}} switch. It tries to emulate,
  4649. as closely as possible, the behavior of Turbo Pascal 7. On the command-line,
  4650. this mode is selected by the \var{-So} switch.
  4651. \begin{enumerate}
  4652. \item Enumeration sizes default to a storage size of 1 byte if there
  4653. are less than 257 elements.
  4654. \item You cannot use the address operator to assign procedural variables.
  4655. \item A forward declaration must not be repeated exactly the same by the
  4656. implementation of a function/procedure. In particular, you can omit the
  4657. parameters when implementing the function or procedure.
  4658. \item Overloading of functions is not allowed.
  4659. \item The Objpas unit is NOT loaded.
  4660. \item Nested comments are not allowed.
  4661. \item You can not use the cvar type.
  4662. \end{enumerate}
  4663. \section{Delphi mode}
  4664. This mode is selected by the \var{{\$MODE DELPHI}} switch. It tries to emulate,
  4665. as closely as possible, the behavior of Delphi 4. On the command-line,
  4666. this mode is selected by the \var{-Sd} switch.
  4667. \begin{enumerate}
  4668. \item You can not use the address operator to assign procedural variables.
  4669. \item A forward declaration must not be repeated exactly the same by the
  4670. implementation of a function/procedure. In particular, you not omit the
  4671. parameters when implementing the function or procedure.
  4672. \item Overloading of functions is not allowed.
  4673. \item Nested comments are not allowed.
  4674. \item The Objpas unit is loaded right after the \file{system} unit. One of the
  4675. consequences of this is that the type \var{Integer} is redefined as
  4676. \var{Longint}.
  4677. \end{enumerate}
  4678. \section{GPC mode}
  4679. This mode is selected by the \var{{\$MODE GPC}} switch. On the command-line,
  4680. this mode is selected by the \var{-Sp} switch.
  4681. \begin{enumerate}
  4682. \item You must use the address operator to assign procedural variables.
  4683. \item A forward declaration must not be repeated exactly the same by the
  4684. implementation of a function/procedure. In particular, you can omit the
  4685. parameters when implementing the function or procedure.
  4686. \item Overloading of functions is not allowed.
  4687. \item The Objpas unit is NOT loaded.
  4688. \item Nested comments are not allowed.
  4689. \item You can not use the cvar type.
  4690. \end{enumerate}
  4691. \section{OBJFPC mode}
  4692. This mode is selected by the \var{{\$MODE OBJFPC}} switch. On the command-line,
  4693. this mode is selected by the \var{-S2} switch.
  4694. \begin{enumerate}
  4695. \item You must use the address operator to assign procedural variables.
  4696. \item A forward declaration must be repeated exactly the same by the
  4697. implementation of a function/procedure. In particular, you can not omit the
  4698. parameters when implementing the function or procedure.
  4699. \item Overloading of functions is allowed.
  4700. \item Nested comments are allowed.
  4701. \item The Objpas unit is loaded right after the \file{system} unit. One of the
  4702. consequences of this is that the type \var{Integer} is redefined as
  4703. \var{Longint}.
  4704. \item You can use the cvar type.
  4705. \item PChars are converted to strings automatically.
  4706. \end{enumerate}
  4707. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4708. % Appendix E
  4709. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4710. \chapter{Using \file{fpcmake}}
  4711. \label{ch:makefile}
  4712. \newcommand{\mvar}[1]{\var{\$(#1)}}
  4713. \newcommand{\fpcmake}{\file{fpcmake}}
  4714. \section{Introduction}
  4715. \fpc comes with a special makefile tool, \fpcmake{}, which can be
  4716. used to construct a \file{Makefile} for use with \gnu \file{make}.
  4717. All sources from the \fpc team are compiled with this system.
  4718. \fpcmake{} uses a file \file{Makefile.fpc} and constructs a file
  4719. \file{Makefile} from it, based on the settings in \file{Makefile.fpc}.
  4720. The following sections explain what settings can be set in \file{Makefile.fpc},
  4721. what variables are set by \var{fpcmake}, what variables it expects to be set,
  4722. and what targets it defines. After that, some settings in the resulting
  4723. \file{Makefile} are explained.
  4724. \section{Functionality}
  4725. \label{se:fpcmakefunctionality}
  4726. \file{fpcmake} generates a makefile, suitable for GNU \file{make},
  4727. which can be used to
  4728. \begin{enumerate}
  4729. \item Compile units and programs, fit for testing or for final distribution.
  4730. \item Compile example units and programs separately.
  4731. \item Install compiled units and programs in standard locations.
  4732. \item Make archives for distribution of the generated programs and units.
  4733. \item Clean up after compilation and tests.
  4734. \end{enumerate}
  4735. \file{fpcmake} knows how the \fpc compiler operates, which command line
  4736. options it uses, how it searches for files and so on; It uses this knowledge
  4737. to construct sensible command-lines.
  4738. Specifically, it constructs the following targets in the final makefile:
  4739. \begin{description}
  4740. \item[all] Makes all units and programs.
  4741. \item[debug] Makes all units and programs with debug info included.
  4742. \item[smart] Makes all units and programs in smartlinked version.
  4743. \item[examples] Makes all example units and programs.
  4744. \item[shared] Makes all units and programs in shared library version
  4745. (currently disabled)
  4746. \item[install] Installs all units and programs.
  4747. \item[sourceinstall] Installs the sources to the \fpc source tree.
  4748. \item[exampleinstall] Installs any example programs and units.
  4749. \item[distinstall] Installs all units and programs, as well as example units
  4750. and programs.
  4751. \item[zipinstall] Makes an archive of the programs and units which can be
  4752. used to install them on another location, i.e. it makes an archive that can
  4753. be used to distribute the units and programs.
  4754. \item[zipsourceinstall] Makes an archive of the program and unit sources
  4755. which can be used to distribute the sources.
  4756. \item[zipexampleinstall] Makes an archive of the example programs and units
  4757. which can be used to install them on another location, i.e. it makes an
  4758. archive that can be used to distribute the example units and programs.
  4759. \item[zipdistinstall] Makes an archive of both the normal as well as the
  4760. example programs and units. This archive can be used to install them on
  4761. another location, i.e. it makes an archive that can be used to
  4762. distribute.
  4763. \item[clean] Cleans all files that are produced by a compilation.
  4764. \item[distclean] Cleans all files that are produced by a compilation, as
  4765. well as any archives, examples or files left by examples.
  4766. \item[cleanall] Same as clean.
  4767. \item[info] Produces some information on the screen about used programs,
  4768. file and directory locations, where things will go when installing and so
  4769. on.
  4770. \end{description}
  4771. Each of these targets can be highly configured, or even totally overridden
  4772. by the configuration file \file{Makefile.fpc}
  4773. \section{Usage}
  4774. \file {fpcmake} reads a \file{Makefile.fpc} and converts it to a
  4775. \file{Makefile} suitable for reading by \gnu \file{make}
  4776. to compile your projects. It is similar in functionality to GNU
  4777. \file{configure} or \file{Imake} for making X projects.
  4778. \fpcmake{} accepts filenames of makefile description files
  4779. as its command-line arguments. For each of these files it will
  4780. create a \file{Makefile} in the same directory where the file is
  4781. located, overwriting any existing file with that name.
  4782. If no options are given, it just attempts to read the file
  4783. \file{Makefile.fpc} in the current directory and tries to
  4784. construct a \file{Makefile} from it if the \var{-m} option is
  4785. given. Any previously existing \file{Makefile} will be erased.
  4786. if the \var{-p} option is given, instead of a \file{Makefile}, a
  4787. \var{Package.fpc} is generated. A \file{Package.fpc} file describes the
  4788. package and it's dependencies on other packages.
  4789. Additionally, the following command-line options are recognized:
  4790. \begin{description}
  4791. \item[-p] A \file{Package.fpc} file is generated.
  4792. \item[-w] A \file{Makefile} is generated.
  4793. \item[-T targets] Support only specified target systems. \var{Targets} is a
  4794. comma-separated list of targets. Only rule for the specified targets
  4795. will be written.
  4796. \item[-v] Be more verbose.
  4797. \item[-q] be quiet.
  4798. \item[-h] Writes a small help message to the screen.
  4799. \end{description}
  4800. % Makefile.fpc format.
  4801. \section{Format of the configuration file}
  4802. This section describes the rules that can be present in the file
  4803. that is fed to \fpcmake{}.
  4804. The file \file{Makefile.fpc} is a plain ASCII file that contains
  4805. a number of pre-defined sections as in a \windows \file{.ini}-file,
  4806. or a Samba configuration file.
  4807. They look more or less as follows:
  4808. \begin{verbatim}
  4809. [package]
  4810. name=mysql
  4811. version=1.0.5
  4812. [target]
  4813. units=mysql_com mysql_version mysql
  4814. examples=testdb
  4815. [require]
  4816. libc=y
  4817. [install]
  4818. fpcpackage=y
  4819. [default]
  4820. fpcdir=../..
  4821. \end{verbatim}
  4822. The following sections are recognized (in alphabetical order):
  4823. \subsection{clean}
  4824. Specifies rules for cleaning the directory of units and programs.
  4825. The following entries are recognized:
  4826. \begin{description}
  4827. \item[units] names of all units that should be removed when cleaning.
  4828. Don't specify extensions, the makefile will append these by itself.
  4829. \item[files] names of files that should be removed. Specify full filenames.
  4830. \end{description}
  4831. \subsection{compiler}
  4832. In this section values for various compiler options can be specified,
  4833. such as the location of several directories and search paths.
  4834. The following general keywords are recognised:
  4835. \begin{description}
  4836. \item[options] The value of this key will be passed on to the compiler as
  4837. options.
  4838. \item[version] If a specific or minimum compiler version is needed to
  4839. compile the units or programs, then this version should be specified here.
  4840. \end{description}
  4841. The following keys can be used to control the location of the various
  4842. directories used by the compiler:
  4843. \begin{description}
  4844. \item[unitdir]
  4845. A colon-separated list of directories that must be added to the unit
  4846. search path of the compiler.
  4847. \item[librarydir]
  4848. A colon-separated list of directories that must be added to the library
  4849. search path of the compiler.
  4850. \item[objectdir]
  4851. A colon-separated list of directories that must be added to the object file
  4852. search path of the compiler.
  4853. \item[targetdir]
  4854. Specifies the directory where the compiled programs should go.
  4855. \item[sourcedir]
  4856. A space separated list of directories where sources can reside.
  4857. This will be used for the \var{vpath} setting of \gnu \file{make}.
  4858. \item[unittargetdir]
  4859. Specifies the directory where the compiled units should go.
  4860. \item[includedir]
  4861. A colon-separated list of directories that must be added to the include file
  4862. search path of the compiler.
  4863. \item[sourcedir]
  4864. \end{description}
  4865. \subsection{Default}
  4866. The \var{default} section contains some default settings. The following keywords
  4867. are recognized:
  4868. \begin{description}
  4869. \item[cpu]
  4870. Specifies the default target processor for which the \file{Makefile}
  4871. should compile the units and programs. By default this is determined from
  4872. the default compiler processor.
  4873. \item[dir]
  4874. Specifies any subdirectories that make should also descend in and
  4875. make the specified target there as well.
  4876. \item[fpcdir]
  4877. Specifies the directory where all the \fpc source trees reside. Below this
  4878. directory the \file{Makefile} expects to find the \file{rtl}, \file{fcl} and
  4879. \file{packages} directory trees.
  4880. \item[rule] Specifies the default rule to execute. \fpcmake{}
  4881. will make sure that this rule is executed if make is executed without
  4882. arguments, i.e., without an explicit target.
  4883. \item[target]
  4884. Specifies the default operating system target for which the \file{Makefile}
  4885. should compile the units and programs. By default this is determined from
  4886. the default compiler target.
  4887. \end{description}
  4888. \subsection{Dist}
  4889. The \var{Dist} section controls the generation of a distribution package.
  4890. A distribution package is a set of archive files (zip files or tar files
  4891. on unix systems) that can be used to distribute the package.
  4892. The following keys can be placed in this section:
  4893. \begin{description}
  4894. \item[destdir] Specifies the directory where the generated zip files should
  4895. be placed.
  4896. \item[zipname] Name of the archive file to be created. If no zipname is
  4897. specified, this defaults to the package name.
  4898. \item[ziptarget] This is the target that should be executed before the
  4899. archive file is made. This defaults to \var{install}.
  4900. \end{description}
  4901. \subsection{Install}
  4902. Contains instructions for installation of the compiler units and programs. The
  4903. following keywords are recognized:
  4904. \begin{description}
  4905. \item[basedir]
  4906. The directory that is used as the base directory for the installation of
  4907. units. Default this is \var{prefix} appended with \var{/lib/fpc/FPC\_VERSION}
  4908. for \linux or simply the \var{prefix} on other platforms.
  4909. \item[datadir] Directory where data files will be installed, i.e. the files
  4910. specified with the \var{Files} keyword.
  4911. \item[fpcpackage] A boolean key. If this key is specified and equals \var{y},
  4912. the files will be installed as a fpc package under the \fpc units directory,
  4913. i.e. under a separate directory. The directory will be named with the name
  4914. specified in the \var{package} section.
  4915. \item[files] extra data files to be installed in the directory specified
  4916. with the \var{datadir} key.
  4917. \item[prefix] is the directory below wchich all installs are done.
  4918. This corresponds to the \var{--prefix} argument to \gnu \file{configure}.
  4919. It is used for the installation of programs and units. By default, this is
  4920. \file{/usr} on \linux, and \file{/pp} on all other platforms.
  4921. \item[units] extra units that should be installed, and which are not part of
  4922. the unit targets. The units in the units target will be installed
  4923. automatically.
  4924. \end{description}
  4925. Units will be installed in the subdirectory \file{units/\$(OS\_TARGET)}
  4926. of the \var{dirbase} entry.
  4927. \subsection{Package}
  4928. If a package (i.e. a collection of units that work together) is being
  4929. compiled, then this section is used to keep package information.
  4930. The following information can be stored:
  4931. \begin{description}
  4932. \item[name] The name of the package. When installing it under the package
  4933. directory, this name will be used to create a directory (unless it is
  4934. overridden by one of the installation options)
  4935. \item[version] The version of this package.
  4936. \item[main] If the package is part of another package, this key can be
  4937. specified to indicate which package it is part of.
  4938. \end{description}
  4939. \subsection{Prerules}
  4940. Anything that is in this section will be inserted as-is in the makefile
  4941. \textit{before} the makefile target rules that are generated by fpcmake.
  4942. This means that any variables that are normally defined by fpcmake rules
  4943. should not be used in this section.
  4944. \subsection{Requires}
  4945. This section is used to indicate dependency on external packages (i.e units)
  4946. or tools. The following keywords can be used:
  4947. \begin{description}
  4948. \item[fpcmake] Minimal version of fpcmake that this \file{makefile.fpc} needs.
  4949. \item[packages] Other packages that should be compiled before this package
  4950. can be compiled. Note that this will also add all packages these packages
  4951. depend on to the dependencies of this package. By default, the \fpc Run-Time
  4952. Library is added to this list.
  4953. \item[libc] a boolean value that indicates whether this package needs the C
  4954. library.
  4955. \item[nortl] a boolean that prevents the addition of the \fpc Run-Time
  4956. Library to the required packages.
  4957. \item[unitdir] These directories will be added to the units search path of
  4958. the compiler.
  4959. \item[packagedir] List of package directories. The packages in these
  4960. directories will be made as well before making the current package.
  4961. \item[tools] A list of executables of extra tools that are required. The
  4962. full path to these tools will be defined in the makefile as a variable with
  4963. the same name as the tool name, only in uppercase. For example, the
  4964. following definition:
  4965. \begin{verbatim}
  4966. tools=upx
  4967. \end{verbatim}
  4968. will lead to the definition of a variable with the name \var{UPX} which will
  4969. contain the full path to the \file{upx} executable.
  4970. \end{description}
  4971. \subsection{Rules}
  4972. In this section dependency rules for the units and any other needed
  4973. targets can be inserted. It will be included at the end of the generated
  4974. makefile. Targets or 'default rules' that are defined by \fpcmake{}
  4975. can be inserted here; if they are not present, then \fpcmake{} will generate
  4976. a rule that will call the generic \var{fpc\_} version. For a list of standard
  4977. targets that will be defined by \fpcmake{}, see \sees{fpcmakefunctionality}.
  4978. For example, it is possible to define a target \var{all:}. If it is not
  4979. defined, then \fpcmake{} will generate one which simply calls
  4980. \var{fpc\_all}:
  4981. \begin{verbatim}
  4982. all: fpc_all
  4983. \end{verbatim}
  4984. The \var{fpc\_all} rule will make all targets as defined in the \var{Target}
  4985. section.
  4986. \subsection{Target}
  4987. This is the most important section of the \file{makefile.fpc} file. Here the
  4988. files are defined which should be compiled when the 'all' target is
  4989. executed.
  4990. The following keywords can be used there:
  4991. \begin{description}
  4992. \item[dirs]
  4993. A space separated list of directories where make should also be run.
  4994. \item[exampledirs]
  4995. A space separated list of directories with example programs. The examples
  4996. target will descend in this list of directories as well.
  4997. \item[examples]
  4998. A space separated list of example programs that need to be compiled when
  4999. the user asks to compile the examples. Do not specify an extension,
  5000. the extension will be appended.
  5001. \item[loaders]
  5002. A space separated list of names of assembler files that must be assembled.
  5003. Don't specify the extension, the extension will be appended.
  5004. \item[programs]
  5005. A space separated list of program names that need to be compiled. Do not
  5006. specify an extension, the extension will be appended.
  5007. \item[rsts] a list of \file{rst} files that needs to be converted to \file{.po}
  5008. files for use with \gnu \file{gettext} and internationalization routines.
  5009. \item[units]
  5010. A space separated list of unit names that need to be compiled. Do not
  5011. specify an extension, just the name of the unit as it would appear un a
  5012. \var{uses} clause is sufficient.
  5013. \end{description}
  5014. \section{Programs needed to use the generated makefile}
  5015. At least the following programs are needed by the generated \file{Makefile}
  5016. to function correctly:
  5017. \begin{description}
  5018. \item[cp] a copy program.
  5019. \item[date] a program that prints the date.
  5020. \item[install] a program to install files.
  5021. \item[make] the \file{make} program, obviously.
  5022. \item[pwd] a program that prints the current working directory.
  5023. \item[rm] a program to delete files.
  5024. \item[zip] the zip archiver program. (on dos/windows/OS2 systems only)
  5025. \item[tar] the tar archiver program (on Unix systems only).
  5026. \end{description}
  5027. These are standard programs on \linux systems, with the possible exception of
  5028. \file{make}. For \dos or \windowsnt, they can be found in the
  5029. file \file{makeutil.zip} on the \fpc FTP site.
  5030. The following programs are optionally needed if you use some special targets.
  5031. Which ones you need are controlled by the settings in the \var{tools} section.
  5032. \begin{description}
  5033. \item[cmp] a \dos and \windowsnt file comparer.
  5034. \item[diff] a file comparer.
  5035. \item[ppdep] the ppdep depency lister. Distributed with \fpc.
  5036. \item[ppufiles] the ppufiles unit file dependency lister. Distributed with \fpc.
  5037. \item[ppumove] the \fpc unit mover.
  5038. \item[sed] the \file{sed} program.
  5039. \item[upx] the UPX executable packer.
  5040. \end{description}
  5041. All of these can also be found on the \fpc FTP site for \dos and \windowsnt.
  5042. \file{ppdep,ppufiles} and \file{ppumove} are distributed with the \fpc
  5043. compiler.
  5044. %
  5045. \section{Variables that affect the generated makefile}
  5046. The makefile generated by \fpcmake{} contains a lot of variables.
  5047. Some of them are set in the makefile itself, others can be set and are taken
  5048. into account when set.
  5049. These variables can be split in two groups:
  5050. \begin{itemize}
  5051. \item Directory variables.
  5052. \item Compiler command-line variables.
  5053. \end{itemize}
  5054. Each group will be discussed separately.
  5055. \subsection{Directory variables}
  5056. The first set of variables controls the directories that are
  5057. recognised in the makefile. They should not be set in the
  5058. \file{Makefile.fpc} file, but can be specified on the commandline.
  5059. \begin{description}
  5060. \item[INCDIR] this is a list of directories, separated by spaces, that will
  5061. be added as include directories to the compiler command-line. Each
  5062. directory in the list is prepended with \var{-I} and added to the
  5063. compiler options.
  5064. \item[UNITDIR] this is a list of directories, separated by spaces, that will
  5065. be added as unit search directories to the compiler command-line. Each
  5066. directory in the list is prepended with \var{-Fu} and added to the
  5067. compiler options.
  5068. \item[LIBDIR] is a list of library paths, separated by spaces. Each
  5069. directory in the list is prepended with \var{-Fl} and added to the
  5070. compiler options.
  5071. \item[OBJDIR] is a list of object file directories, separated by spaces, that is
  5072. added to the object files path, i.e. Each directory in the list is prepended with
  5073. \var{-Fo}.
  5074. \end{description}
  5075. \subsection{Compiler command-line variables }
  5076. The following variable can be set on the \file{make} command-line,
  5077. they will be recognised and integrated in the compiler command-line options.:
  5078. \begin{description}
  5079. \item[CREATESMART] If this variable is defined, it tells the compiler to
  5080. create smartlinked units. Adds \var{-CX} to the command-line options.
  5081. \item[DEBUG] If defined, this will cause the compiler to include debug information in
  5082. the generated units and programs. It adds \var{-gl} to the compiler
  5083. command-line, and will define the \var{DEBUG} define.
  5084. \item[LINKSMART] Defining this variable tells the compiler to use smartlinking.
  5085. It adds \var{-XX} to the compiler command-line options.
  5086. \item[OPT] Any options that you want to pass to the compiler. The contents
  5087. of \var{OPT} is simply added to the compiler command-line.
  5088. \item[OPTDEF] Are optional defines, added to the command-line of the
  5089. compiler. They get \var{-d} prepended to them.
  5090. \item[OPTIMIZE] if this variable is defined, this will add \var{-OG2p3} to
  5091. the command-line options.
  5092. \item[RELEASE] if this variable is defined, this will add the \var{-Xs -OG2p3 -n}
  5093. options to the command-line options, and will define the \var{RELEASE} define.
  5094. \item[STRIP] if this variable is defined, this will add the \var{-Xs} option
  5095. to the command-line options.
  5096. \item[VERBOSE] if this variable is defined, then \var{-vnwi} will be added
  5097. to the command-line options.
  5098. \end{description}
  5099. \section{Variables set by \fpcmake{}}
  5100. The makefile generated by \fpcmake{} contains a lot of makefile variables.
  5101. \fpcmake{} will write all of the keys in the \file{makefile.fpc} as
  5102. makefile variables in the form \var{SECTION\_KEYNAME}. This means that the
  5103. following section:
  5104. \begin{verbatim}
  5105. [package]
  5106. name=mysql
  5107. version=1.0.5
  5108. \end{verbatim}
  5109. will result in the following variable definitions:
  5110. \begin{verbatim}
  5111. override PACKAGE_NAME=mysql
  5112. override PACKAGE_VERSION=1.0.5
  5113. \end{verbatim}
  5114. Most targets and rules are constructed using these variables. They will be
  5115. listed below, together with other variables that are defined by \fpcmake{}.
  5116. The following sets of variables are defined:
  5117. \begin{itemize}
  5118. \item Directory variables.
  5119. \item Program names.
  5120. \item File extensions.
  5121. \item Target files.
  5122. \end{itemize}
  5123. Each of these sets is discussed in the subsequent:
  5124. \subsection{Directory variables}
  5125. The following compiler directories are defined by the makefile:
  5126. \begin{description}
  5127. \item[BASEDIR] is set to the current directory if the \file{pwd} command is
  5128. available. If not, it is set to '.'.
  5129. \item[COMPILER\_INCDIR] is a space-separated list of library paths. Each
  5130. directory in the list is prepended with \var{-Fl} and added to the
  5131. compiler options. Set by the \var{incdir} keyword in the \var{Compiler} section.
  5132. \item[COMPILER\_LIBDIR] is a space-separated list of library paths. Each
  5133. directory in the list is prepended with \var{-Fl} and added to the
  5134. compiler options. Set by the \var{libdir} keyword in the \var{Compiler} section.
  5135. \item[COMPILER\_OBJDIR] is a list of object file directories, separated by
  5136. spaces. Each directory in the list is prepended with \var{-Fo} and
  5137. added to the compiler options.
  5138. Set by the \var{objdir} keyword in the \var{Compiler} section.
  5139. \item[COMPILER\_TARGETDIR] This directory is added as the output directory of
  5140. the compiler, where all units and executables are written, i.e. it gets
  5141. \var{-FE} prepended. It is set by the \var{targtdir} keyword in the
  5142. \var{Compiler} section.
  5143. \item[COMPILER\_TARGETUNITDIR] If set, this directory is added as the output directory of
  5144. the compiler, where all units and executables are written, i.e. it gets
  5145. \var{-FU} prepended.It is set by the \var{targtdir} keyword in the
  5146. \var{Dirs} section.
  5147. \item[COMPILER\_UNITDIR] is a list of unit directories, separated by spaces.
  5148. Each directory in the list is prepended with \var{-Fu} and is added to the
  5149. compiler options.
  5150. Set by the \var{unitdir} keyword in the \var{Compiler} section.
  5151. \item[GCCLIBDIR] (\linux only) is set to the directory where \file{libgcc.a}
  5152. is. If \var{needgcclib} is set to \var{True} in the \var{Libs} section, then
  5153. this directory is added to the compiler commandline with \var{-Fl}.
  5154. \item[OTHERLIBDIR] is a space-separated list of library paths. Each
  5155. directory in the list is prepended with \var{-Fl} and added to the
  5156. compiler options. If it is not defined on linux, then the contents of
  5157. the \file{/etc/ld.so.conf} file is added.
  5158. \end{description}
  5159. The following directories are used for installs:
  5160. \begin{description}
  5161. \item[INSTALL\_BASEDIR] is the base for all directories where units are
  5162. installed. By default, On \linux, this is set to
  5163. \mvar{INSTALL\_PREFIX}\var{/lib/fpc/}\mvar{RELEASEVER}.\\ On other systems,
  5164. it is set to \mvar{PREFIXINSTALLDIR}. You can also set it with the
  5165. \var{basedir} variable in the \var{Install} section.
  5166. \item[INSTALL\_BINDIR] is set to \mvar{INSTALL\_BASEDIR}/\var{bin} on \linux,
  5167. and\\ \mvar{INSTALL\_BASEDIR}/\var{bin}/\mvar{OS\_TARGET} on other systems.
  5168. This is the place where binaries are installed.
  5169. \item[INSTALL\_DATADIR] The directory where data files are installed. Set by
  5170. the \var{Data} key in the \var{Install} section.
  5171. \item[INSTALL\_LIBDIR] is set to \mvar{INSTALL\_PREFIX}/lib on \linux,\\
  5172. and \mvar{INSTALL\_UNITDIR} on other systems.
  5173. \item[INSTALL\_PREFIX] is set to \file{/usr/local} on \linux, \file{/pp} on \dos
  5174. or \windowsnt. Set by the \var{prefix} keyword in the \var{Install}
  5175. section.
  5176. \item[INSTALL\_UNITDIR] is where units will be installed. This is set to\\
  5177. \mvar{INSTALL\_BASEDIR}/units/\mvar{OS\_TARGET}. If the units are compiled
  5178. as a package, \mvar{PACKAGE\_NAME} is added to the directory.
  5179. \end{description}
  5180. \subsection{Target variables}
  5181. The second set of variables controls the targets that are constructed
  5182. by the makefile. They are created by \fpcmake{}, so you can use
  5183. them in your rules, but you shouldn't assign values to them yourself.
  5184. \begin{description}
  5185. \item[TARGET\_DIRS] This is the list of directories that make will descend
  5186. into when compiling. Set by the \var{Dirs} key in the \var{Target} section?
  5187. \item[TARGET\_EXAMPLES] The list of examples programs that must be compiled.
  5188. Set by the \var{examples} key in the \var{Target} section.
  5189. \item[TARGET\_EXAMPLEDIRS] the list of directories that make will descend
  5190. into when compiling examples. Set by the \var{exampledirs} key in the
  5191. \var{Target} section.
  5192. \item[TARGET\_LOADERS] is a list of space-separated names that identify
  5193. loaders to be compiled. This is mainly used in the compiler's RTL sources.
  5194. It is set by the \var{loaders} keyword in the \var{Targets} section.
  5195. \item[TARGET\_PROGRAMS] This is a list of executable names that will be compiled.
  5196. the makefile appends \mvar{EXEEXT} to these names. It is set by the
  5197. \var{programs} keyword in the \var{Target} section.
  5198. \item[TARGET\_UNITS] This is a list of unit names that will be compiled. The
  5199. makefile appends \mvar{PPUEXT} to each of these names to form the unit file
  5200. name. The sourcename is formed by adding \mvar{PASEXT}.
  5201. It is set by the \var{units} keyword in the \var{Target} section.
  5202. \item[ZIPNAME] is the name of the archive that will be created by the
  5203. makefile.
  5204. It is set by the \var{zipname} keyword in the \var{Zip} section.
  5205. \item[ZIPTARGET] is the target that is built before the archive is made.
  5206. this target is built first. If successful, the zip archive will be made.
  5207. It is set by the \var{ziptarget} keyword in the \var{Zip} section.
  5208. \end{description}
  5209. \subsection{Compiler command-line variables}
  5210. The following variables control the compiler command-line:
  5211. \begin{description}
  5212. \item[CPU\_SOURCE] the target CPU type is added as a define to the compiler
  5213. command line. This is determined by the Makefile itself.
  5214. \item[CPU\_TARGET] the target CPU type is added as a define to the compiler
  5215. command line. This is determined by the Makefile itself.
  5216. \item[OS\_SOURCE] What platform the makefile is used on. Detected
  5217. automatically.
  5218. \item[OS\_TARGET] What platform will be compiled for. Added to the
  5219. compiler command-line with a \var{-T} prepended.
  5220. \end{description}
  5221. \subsection{Program names}
  5222. The following variables are program names, used in makefile targets.
  5223. \begin{description}
  5224. \item[AS] The assembler. Default set to \file{as}.
  5225. \item[COPY] a file copy program. Default set to \file{cp -fp}.
  5226. \item[COPYTREE] a directory tree copy program. Default set to \file{cp -frp}.
  5227. \item[CMP] a program to compare files. Default set to \var{cmp}.
  5228. \item[DEL] a file removal program. Default set to \file{rm -f}.
  5229. \item[DELTREE] a directory removal program. Default set to \file{rm -rf}.
  5230. \item[DATE] a program to display the date.
  5231. \item[DIFF] a program to produce diff files.
  5232. \item[ECHO] an echo program.
  5233. \item[FPC] the Free Pascal compiler executable. Default set to
  5234. \var{ppc386.exe}
  5235. \item[INSTALL] a program to install files. Default set to \file{install -m
  5236. 644} on \linux.
  5237. \item[INSTALLEXE] a program to install executable files. Default set to \file{install -m
  5238. 755} on \linux.
  5239. \item[LD] The linker. Default set to \file{ld}.
  5240. \item[LDCONFIG] (\linux only) the program used to update the loader cache.
  5241. \item[MKDIR] a program to create directories if they don't exist yet. Default
  5242. set to \file{install -m 755 -d}
  5243. \item[MOVE] a file move program. Default set to \file{mv -f}
  5244. \item[PP] the Free Pascal compiler executable. Default set to
  5245. \var{ppc386.exe}
  5246. \item[PPAS] the name of the shell script created by the compiler if the
  5247. \var{-s} option is specified. This command will be executed after
  5248. compilation, if the \var{-s} option was detected among the options.
  5249. \item[PPUMOVE] the program to move units into one big unit library.
  5250. \item[PWD] the pwd program.
  5251. \item[SED] a stream-line editor program. Default set to \file{sed}.
  5252. \item[UPX] an executable packer to compress your executables into
  5253. self-extracting compressed executables.
  5254. \item[ZIPPROG] a zip program to compress files. zip targets are made with
  5255. this program
  5256. \end{description}
  5257. \subsection{File extensions}
  5258. The following variables denote extensions of files. These variables include
  5259. the \var{.} (dot) of the extension. They are appended to object names.
  5260. \begin{description}
  5261. \item[ASMEXT] is the extension of assembler files produced by the compiler.
  5262. \item[LOADEREXT] is the extension of the assembler files that make up the
  5263. executable startup code.
  5264. \item[OEXT] is the extension of the object files that the compiler creates.
  5265. \item[PACKAGESUFFIX] is a suffix that is appended to package names in zip
  5266. targets. This serves so packages can be made for different OSes.
  5267. \item[PPLEXT] is the extension of shared library unit files.
  5268. \item[PPUEXT] is the extension of default units.
  5269. \item[RSTEXT] is the extension of the \file{.rst} resource string files.
  5270. \item[SHAREDLIBEXT] is the extension of shared libraries.
  5271. \item[SMARTEXT] is the extension of smartlinked unit assembler files.
  5272. \item[STATICLIBEXT] is the extension of static libraries.
  5273. \end{description}
  5274. \subsection{Target files}
  5275. The following variables are defined to make targets and rules easier:
  5276. \begin{description}
  5277. \item[COMPILER] is the complete compiler commandline, with all options
  5278. added, after all \file{Makefile} variables have been examined.
  5279. \item[DATESTR] contains the date.
  5280. \item[UNITPPUFILES] a list of unit files that will be made. This is just
  5281. the list of unit objects, with the correct unit extension appended.
  5282. \end{description}
  5283. \section{Rules and targets created by \fpcmake{}}
  5284. The \var{makefile.fpc} defines a series of targets, which can be called by
  5285. your own targets. They have names that resemble default names (such as
  5286. 'all', 'clean'), only they have \var{fpc\_} prepended.
  5287. \subsection{Pattern rules}
  5288. The makefile makes the following pattern rules:
  5289. \begin{description}
  5290. \item[units] how to make a pascal unit form a pascal source file.
  5291. \item[executables] how to make an executable from a pascal source file.
  5292. \item[object file] how to make an object file from an assembler file.
  5293. \end{description}
  5294. \subsection{Build rules}
  5295. The following build targets are defined:
  5296. \begin{description}
  5297. \item[fpc\_all] target that builds all units and executables as well as
  5298. loaders. If \var{DEFAULTUNITS} is defined, executables are excluded from the
  5299. targets.
  5300. \item[fpc\_debug] the same as \var{fpc\_all}, only with debug information
  5301. included.
  5302. \item[fpc\_exes] target to make all executables in \var{EXEOBJECTS}.
  5303. \item[fpc\_loaders] target to make all files in \var{LOADEROBJECTS}.
  5304. \item[fpc\_packages] target to make all packages that are needed to make
  5305. the files.
  5306. \item[fpc\_shared] target that makes all units as dynamic libraries.
  5307. \item[fpc\_smart] target that makes all units as smartlinked units.
  5308. \item[fpc\_units] target to make all units in \var{UNITOBJECTS}.
  5309. \end{description}
  5310. \subsection{Cleaning rules}
  5311. The following cleaning targets are defined:
  5312. \begin{description}
  5313. \item[fpc\_clean] cleans all files that result when \var{fpc\_all} was made.
  5314. \item[fpc\_distclean] is the same as both previous target commands, but also
  5315. deletes all object, unit and assembler files that are present.
  5316. \end{description}
  5317. \subsection{archiving rules}
  5318. The following archiving targets are defined:
  5319. \begin{description}
  5320. \item[fpc\_zipdistinstall] Target to make a distribution install of the
  5321. package.
  5322. \item[fpc\_zipinstall] Target to make an install zip of the compiled units
  5323. of the package.
  5324. \item[fpc\_zipexampleinstall] Target to make a zip of the example files.
  5325. \item[fpc\_zipsourceinstall] Target to make a zip of the source files.
  5326. \end{description}
  5327. The zip is made uzing the \var{ZIPEXE} program. Under \linux, a
  5328. \file{.tar.gz} file is created.
  5329. \subsection{Installation rules}
  5330. \begin{description}
  5331. \item[fpc\_distinstall] target which calls the \var{install} and
  5332. \var{exampleinstall} targets.
  5333. \item[fpc\_install] target to install the units.
  5334. \item[fpc\_sourceinstall] target to install the sources (in case a
  5335. distribution is made)
  5336. \item[fpc\_exampleinstall] target to install the examples. (in case
  5337. a distribution is made)
  5338. \end{description}
  5339. \subsection{Informative rules}
  5340. There is only one target which produces information about the used
  5341. variables, rules and targets: \var{fpc\_info}.
  5342. The following information about the makefile is presented:
  5343. \begin{itemize}
  5344. \item general configuration information: the location of
  5345. the makefile, the compiler version, target OS, CPU.
  5346. \item the directories, used by the compiler.
  5347. \item all directories where files will be installed.
  5348. \item all objects that will be made.
  5349. \item all defined tools.
  5350. \end{itemize}
  5351. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5352. % Appendix F
  5353. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5354. \chapter{Compiling the compiler}
  5355. \label{ch:AppF}
  5356. \section{Introduction}
  5357. The \fpc team releases at intervals a completely prepared package, with
  5358. compiler and units all ready to use, the so-called releases. After a
  5359. release, work on the compiler continues, bugs are fixed and features are
  5360. added. The \fpc team doesn't make a new release whenever they change
  5361. something in the compiler, instead the sources are available for anyone to
  5362. use and compile. Compiled versions of RTL and compiler are also made daily,
  5363. and put on the web.
  5364. There are, nevertheless, circumstances when the compiler must be recompiled
  5365. manually. When changes are made to compiler code, or when the compiler is
  5366. downloaded through CVS.
  5367. There are essentially 2 ways of recompiling the compiler: by hand, or using
  5368. the makefiles. Each of these methods will be discussed.
  5369. \section{Before starting}
  5370. To compile the compiler easily, it is best to keep the following directory
  5371. structure (a base directory of \file{/pp/src} is supposed, but that may be
  5372. different):
  5373. \begin{verbatim}
  5374. /pp/src/Makefile
  5375. /makefile.fpc
  5376. /rtl/linux
  5377. /inc
  5378. /i386
  5379. /...
  5380. /compiler
  5381. \end{verbatim}
  5382. When the makefiles should be used, the above directory tree must be used.
  5383. The compiler and rtl source are zipped in such a way that when both are
  5384. unzipped in the same directory (\file{/pp/src} in the above) the above
  5385. directory tree results.
  5386. There are 2 ways to start compiling the compiler and RTL. Both ways must be
  5387. used, depending on the situation. Usually, the RTL must be compiled first,
  5388. before compiling the compiler, after which the compiler is compiled using
  5389. the current compiler. In some special cases the compiler must be compiled
  5390. first, with a previously compiled RTL.
  5391. How to decide which should be compiled first? In general, the answer is that
  5392. the RTL should be compiled first. There are 2 exceptions to this rule:
  5393. \begin{enumerate}
  5394. \item The first case is when some of the internal routines in the RTL
  5395. have changed, or if new internal routines appeared. Since the OLD compiler
  5396. doesn't know about these changed internal routines, it will emit function
  5397. calls that are based on the old compiled RTL, and hence are not correct.
  5398. Either the result will not link, or the binary will give errors.
  5399. \item The second case is when something is added to the RTL that the
  5400. compiler needs to know about (a new default assembler mechanism, for
  5401. example).
  5402. \end{enumerate}
  5403. How to know if one of these things has occurred? There is no way to know,
  5404. except by mailing the \fpc team. When the compiler cannot be recompiled
  5405. when first compiling the RTL, then try the other way.
  5406. \section{Compiling using \file{make}}
  5407. When compiling with \var{make} it is necessary to have the above directory
  5408. structure. Compiling the compiler is achieved with the target \var{cycle}.
  5409. Under normal circumstances, recompiling the compiler is limited to the
  5410. following instructions (assuming you start in directory \file{/pp/src}):
  5411. \begin{verbatim}
  5412. cd compiler
  5413. make cycle
  5414. \end{verbatim}
  5415. This will work only if the \file{makefile} is installed correctly and
  5416. if the needed tools are present in the \var{PATH}. Which tools must be
  5417. installed can be found in appendix \ref{ch:makefile}.
  5418. The above instructions will do the following:
  5419. \begin{enumerate}
  5420. \item Using the current compiler, the RTL is compiled in the correct
  5421. directory, which is determined by the OS. e.g. under \linux,
  5422. the RTL is compiled in directory \file{rtl/linux}.
  5423. \item The compiler is compiled using the newly compiled RTL. If successful,
  5424. the newly compiled compiler executable is copied to a temporary executable.
  5425. \item Using the temporary executable from the previous step, the RTL is
  5426. re-compiled.
  5427. \item Using the temporary executable and the newly compiled RTL from the
  5428. last step, the compiler is compiled again.
  5429. \end{enumerate}
  5430. The last two steps are repeated 3 times, until three passes have been made or
  5431. until the generated compiler binary is equal to the binary it was compiled
  5432. with. This process ensures that the compiler binary is correct.
  5433. Compiling for another target:
  5434. When compiling the compiler for another target, it is necessary to specify
  5435. the \var{OS\_TARGET} makefile variable. It can be set to the following
  5436. values: \var{win32}, \var{go32v2}, \var{os2} and \var{linux}.
  5437. As an example, cross-compilation for the go32v2 target from the win32 target
  5438. is chosen:
  5439. \begin{verbatim}
  5440. cd compiler
  5441. make cycle OS_TARGET=go32v2
  5442. \end{verbatim}
  5443. This will compile the go32v2 RTL, and compile a \var{go32v2} compiler.
  5444. When compiling a new compiler and the compiler should be compiled using an
  5445. existing compiled RTL, the \var{all} target must be used, and another RTL
  5446. directory than the default (which is the \file{../rtl/\$(OS\_TARGET)}
  5447. directory) must be indicated. For instance, assuming that the compiled RTL
  5448. units are in \var{/pp/rtl}, typing
  5449. \begin{verbatim}
  5450. cd compiler
  5451. make clean
  5452. make all UNITDIR=/pp/rtl
  5453. \end{verbatim}
  5454. should use the RTL from the \var{/pp/rtl} dirrectory.
  5455. This will then compile the compiler using the RTL units in \file{/pp/rtl}.
  5456. After this has been done, the 'make cycle' can be used, starting with this
  5457. compiler:
  5458. \begin{verbatim}
  5459. make cycle PP=./ppc386
  5460. \end{verbatim}
  5461. This will do the \var{make cycle} from above, but will start with the compiler
  5462. that was generated by the \var{make all} instruction.
  5463. In all cases, many options can be passed to \var{make} to influence the
  5464. compile process. In general, the makefiles add any needed compiler options
  5465. to the command-line, so that the RTL and compiler can be compiled.
  5466. Additional options (e.g. optimization options) can be specified by passing them in
  5467. \var{OPT}.
  5468. \section{Compiling by hand}
  5469. Compiling by hand is difficult and tedious, but can be done. The
  5470. compilation of RTL and compiler will be treated separately.
  5471. \subsection{Compiling the RTL}
  5472. To recompile the RTL, so a new compiler can be built, at least the following
  5473. units must be built, in the order specified:
  5474. \begin{enumerate}
  5475. \item[loaders] the program stubs, that are the startup code for each pascal
  5476. program. These files have the \file{.as} extension, because they are written
  5477. in assembler. They must be assembled with the \gnu \file{as} assembler. These stubs
  5478. are in the OS-dependent directory, except for \linux, where they are in a
  5479. processor dependent subdirectory of the \linux directory (\file{i386} or
  5480. \file{m68k}).
  5481. \item[system] the \file{system} unit. This unit is named differently on different
  5482. systems:
  5483. \begin{itemize}
  5484. \item Only on GO32v2, it's called \file{system}.
  5485. \item For \linux it's called \file{syslinux}.
  5486. \item For \windowsnt it's called \file{syswin32}.
  5487. \item For \ostwo it's called \file{sysos2}
  5488. \end{itemize}
  5489. This unit resides in the OS-dependent subdirectories of the RTL.
  5490. \item[strings] The strings unit. This unit resides in the \file{inc}
  5491. subdirectory of the RTL.
  5492. \item[dos] The \file{dos} unit. It resides in the OS-dependent subdirectory
  5493. of the RTL. Possibly other units will be compiled as a consequence of trying
  5494. to compile this unit (e.g. on \linux, the \file{linux} unit will be
  5495. compiled, on go32, the \file{go32} unit will be compiled).
  5496. \item[objects] the objects unit. It resides in the \file{inc} subdirectory
  5497. of the RTL.
  5498. \end{enumerate}
  5499. To compile these units on a i386, the following statements will do:
  5500. \begin{verbatim}
  5501. ppc386 -Tlinux -b- -Fi../inc -Fi../i386 -FE. -di386 -Us -Sg syslinux.pp
  5502. ppc386 -Tlinux -b- -Fi../inc -Fi../i386 -FE. -di386 ../inc/strings.pp
  5503. ppc386 -Tlinux -b- -Fi../inc -Fi../i386 -FE. -di386 dos.pp
  5504. ppc386 -Tlinux -b- -Fi../inc -Fi../i386 -FE. -di386 ../inc/objects.pp
  5505. \end{verbatim}
  5506. These are the minimum command-line options, needed to compile the RTL.
  5507. For another processor, the \var{i386} should be changed into the appropriate
  5508. processor. For another operating system (target) the
  5509. \file{syslinux} should be changed in the appropriate system unit file,
  5510. and the target OS setting (\var{-T}) must be set accordingly.
  5511. Depending on the target OS there are other units that can be
  5512. compiled, but which are not strictly needed to recompile the compiler.
  5513. The following units are available for all plaforms:
  5514. \begin{description}
  5515. \item[objpas] Needed for Delphi mode. Needs \var{-S2} as an option. Resides
  5516. in the \file{objpas} subdirectory.
  5517. \item[sysutils] many utility functions, like in Delphi. Resides in the
  5518. \file{objpas} directory, and needs \var{-S2} to compile.
  5519. \item[typinfo] functions to access RTTI information, like Delphi. Resides in
  5520. the \file{objpas} directory.
  5521. \item[math] math functions like in Delphi. Resides in the \file{objpas}
  5522. directory.
  5523. \item[mmx] extensions for MMX class Intel processors. Resides in
  5524. in the \file{i386} directory.
  5525. \item[getopts] a GNU compatible getopts unit. resides in the \file{inc}
  5526. directory.
  5527. \item[heaptrc] to debug the heap. resides in the \file{inc} directory.
  5528. \end{description}
  5529. \subsection{Compiling the compiler}
  5530. Compiling the compiler can be done with one statement. It's always best to
  5531. remove all units from the compiler directory first, so something like
  5532. \begin{verbatim}
  5533. rm *.ppu *.o
  5534. \end{verbatim}
  5535. on \linux, and on \dos
  5536. \begin{verbatim}
  5537. del *.ppu
  5538. del *.o
  5539. \end{verbatim}
  5540. After this, the compiler can be compiled with the following command-line:
  5541. \begin{verbatim}
  5542. ppc386 -Tlinux -Fu../rtl/linux -di386 -dGDB pp.pas
  5543. \end{verbatim}
  5544. So, the minimum options are:
  5545. \begin{enumerate}
  5546. \item The target OS. Can be skipped when compiling for the same target as
  5547. the compiler which is being used.
  5548. \item A path to an RTL. Can be skipped if a correct fpc.cfg configuration
  5549. is on the system. If the compiler should be compiled with the RTL that was
  5550. compiled first, this should be \file{../rtl/OS} (replace the OS with the
  5551. appropriate operating system subdirectory of the RTL).
  5552. \item A define with the processor for which the compiler is compiled for. Required.
  5553. \item \var{-dGDB}. Required.
  5554. \item \var{-Sg} is needed, some parts of the compiler use \var{goto}
  5555. statements (to be specific: the scanner).
  5556. \end{enumerate}
  5557. So the absolute minimal command line is
  5558. \begin{verbatim}
  5559. ppc386 -di386 -dGDB -Sg pp.pas
  5560. \end{verbatim}
  5561. Some other command-line options can be used, but the above are the
  5562. minimum. A list of recognised options can be found in \seet{FPCdefines}.
  5563. \begin{FPCltable}{ll}{Possible defines when compiling FPC}{FPCdefines}
  5564. Define & does what \\ \hline
  5565. TP & Needed to compile the compiler with Turbo or Borland Pascal. \\
  5566. GDB & Support of the GNU Debugger (required switch). \\
  5567. I386 & Generate a compiler for the Intel i386+ processor family. \\
  5568. M68K & Generate a compiler for the M680x0 processor family. \\
  5569. EXTDEBUG & Some extra debug code is executed. \\
  5570. MEMDEBUG & Some memory usage information is displayed. \\
  5571. SUPPORT\_MMX & only i386: enables the compiler switch \var{MMX} which \\
  5572. &allows the compiler to generate MMX instructions.\\
  5573. EXTERN\_MSG & Don't compile the msgfiles in the compiler, always use \\
  5574. & external messagefiles (default for TP).\\
  5575. LOGSECONDPASS & Write compiler node information in assembler output. \\
  5576. NOOPT & Do not include the optimizer in the compiler. \\
  5577. \hline
  5578. \end{FPCltable}
  5579. This list may be subject to change, the source file \file{pp.pas} always
  5580. contains an up-to-date list.
  5581. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5582. % Appendix G : Compiler defines
  5583. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5584. \chapter{Compiler defines during compilation}
  5585. \label{ch:AppG}
  5586. This appendix describes the possible defines when compiling programs
  5587. using \fpc. A brief explanation of the define, and when it is used
  5588. is also given.
  5589. \begin{FPCltable}{ll}{Possible defines when compiling using FPC}{FPCOutdefines}
  5590. Define & description \\ \hline
  5591. FPC\_LINK\_DYNAMIC & Defined when the output will be linked dynamically.\\
  5592. & This is defined when using the -XD compiler switch.\\
  5593. FPC\_LINK\_STATIC & Defined when the output will be linked statically.\\
  5594. & This is the default mode. \\
  5595. FPC\_LINK\_SHARED & Defined when the output will be smartlinked.\\
  5596. & This is defined when using the -XX compiler switch.\\
  5597. FPC\_PROFILE & Defined when profiling code is added to program.\\
  5598. & This is defined when using the -pg compiler switch.\\
  5599. FPK & Always defined for \fpc. \\
  5600. FPC & Always defined for \fpc. \\
  5601. VER1 & Always defined for \fpc version 1.x.x. \\
  5602. VER1\_0 & Always defined for \fpc version 1.0.x. \\
  5603. ENDIAN\_LITTLE & Defined when the \fpc target is a little-endian processor \\
  5604. & (80x86, Alpha, ARM). \\
  5605. ENDIAN\_BIG & Defined when the \fpc target is a big-endian processor \\
  5606. & (680x0, PowerPC, SPARC, MIPS). \\
  5607. FPU\_EMULATION & Defined when the \fpc target uses floating-point software \\
  5608. & emulation. \\
  5609. FPC\_DELPHI & \fpc is in Delphi mode, either using compiler switch -Sd or \\
  5610. & using the \var{\$MODE DELPHI} directive. \\
  5611. FPC\_OBJFPC & \fpc is in Delphi mode, either using compiler switch -S2 or \\
  5612. & using the \var{\$MODE OBJFPC} directive. \\
  5613. FPC\_TP & \fpc is in Turbo Pascal mode, either using compiler switch -So or \\
  5614. & using the \var{\$MODE TP} directive. \\
  5615. FPC\_GPC & \fpc is in GNU Pascal mode, either using compiler switch -Sp or \\
  5616. & using the \var{\$MODE GPC} directive. \\
  5617. \end{FPCltable}
  5618. \begin{remark}
  5619. The \var{ENDIAN\_LITTLE} and \var{ENDIAN\_BIG} defines were added
  5620. starting from \fpc version 1.0.5. The \var{FPU\_EMULATION} define
  5621. was added starting from \fpc version 1.0.7.
  5622. \end{remark}
  5623. \begin{FPCltable}{ll}{Possible CPU defines when compiling using FPC}{FPCCPUdefines}
  5624. Define & When defined? \\ \hline
  5625. CPU86 & \fpc target is an Intel 80x86 or compatible.\\
  5626. CPU87 & \fpc target is an Intel 80x86 or compatible.\\
  5627. CPUI386 & \fpc target is an Intel 80386 or later.\\
  5628. CPU68k & \fpc target is a Motorola 680x0 or compatible.\\
  5629. CPUM68020 & \fpc target is a Motorola 68020 or later.\\
  5630. CPU68 & \fpc target is a Motorola 680x0 or compatible.\\
  5631. CPUSPARC & \fpc target is a SPARC v7 or compatible.\\
  5632. CPUALPHA & \fpc target is an Alpha AXP or compatible.\\
  5633. CPUPOWERPC & \fpc target is a 32-bit PowerPC or compatible.\\
  5634. \end{FPCltable}
  5635. \begin{FPCltable}{ll}{Possible defines when compiling using target OS}{FPCOSdefines}
  5636. Target operating system & Defines \\ \hline
  5637. linux & LINUX, UNIX\\
  5638. freebsd & FREEBSD, BSD, LINUX, UNIX\\
  5639. netbsd & NETBSD, BSD, LINUX, UNIX\\
  5640. sunos & SUNOS, SOLARIS, UNIX\\
  5641. go32v2 & GO32V2, DPMI\\
  5642. os2 & OS2\\
  5643. Windows 32-bit & WIN32\\
  5644. Classic Amiga & AMIGA\\
  5645. Atari TOS & ATARI\\
  5646. Classic Macintosh & MAC\\
  5647. PalmOS & PALMOS\\
  5648. BeOS & BEOS, UNIX\\
  5649. QNX RTP & QNX, UNIX
  5650. \end{FPCltable}
  5651. \begin{remark}
  5652. The \unix define was added starting from \fpc version 1.0.5.
  5653. \end{remark}
  5654. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5655. % Appendix H : Operating system specific behavior
  5656. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5657. \chapter{Operating system specific behavior}
  5658. \label{ch:AppH}
  5659. This appendix describes some special behaviors which vary
  5660. from operating system to operating system. This is described
  5661. in \seet{OSBehave}. The GCC saved registers indicates what
  5662. registers are saved when certain declaration modifiers are used.
  5663. \begin{FPCltable}{lcr}{Operating system specific behavior}{OSBehave}
  5664. Operating systems & Min. param. stack align & GCC saved registers\\
  5665. \hline
  5666. Amiga & 2 & D2..D7,A2..A5\\
  5667. Atari & 2 & D2..D7,A2..A5\\
  5668. BeOS-x86 & 4 & ESI, EDI, EBX\\
  5669. DOS & 2 & ESI, EDI, EBX\\
  5670. FreeBSD & 4 & ESI, EDI, EBX\\
  5671. linux-m68k & & D2..D7,A2..A5\\
  5672. linux-x86 & 4 & ESI, EDI, EBX\\
  5673. MacOS-68k & & D2..D7,A2..A5\\
  5674. NetBSD-x86 & & ESI, EDI, EBX\\
  5675. NetBSD-m68k & & D2..D7,A2..A5\\
  5676. OS/2 & 4 & ESI, EDI, EBX\\
  5677. PalmOS & 2 & D2..D7,A2..A5\\
  5678. QNX-x86 & & ESI, EDI, EBX\\
  5679. Solaris-x86 & 4 & ESI, EDI, EBX\\
  5680. Win32 & 4 & ESI, EDI, EBX\\
  5681. \hline
  5682. \end{FPCltable}
  5683. \end{document}