stormc v3 users manual

214
Projektverwaltung StormC The professional choice Users manual ANSI C/C++ Development- system for the Amiga

Upload: phibel1

Post on 06-Mar-2015

60 views

Category:

Documents


11 download

TRANSCRIPT

Page 1: StormC V3 Users Manual

Projektverwaltung5

StormC User Manual

1

StormC

The professional choice

Users manual

ANSI C/C++ Development-system for the Amiga

Page 2: StormC V3 Users Manual

C

OPYRIGHT

Copyright

STORMC C/C++ DEVELOPMENT SYSTEM

Software and manual

(c) 1995-1999 HAAGE & PARTNER Computer GmbH

Authors:Jochen BecherEditorProject ManagerDebuggerProfilerLibrariesLibrarianScreenManagerWizard.Library

Jens GelharANSI C CompilerC++ CompilerPPC-FrontendpOS-Compiler

Michael RockOptimizing LinkerPatcherFD2PRAGMAPPC-Backend

Markus NerdingJeroen T. VermeulenWouter van OortmerssenPeter-Frans HollantsGeorges GoncalvesKersten EmmrichManual Translation

Peter (dreamy) TraskalikHartwig HaageGraphics

All rights reserved. This manual and the accompanyingsoftware are copyrighted. They may not be reproduced inany form (whether partically or in whole) by any means ofprocedure, sent, multiplied and/or spread or be translatedinto another language.

HAAGE & PARTNER assumes no responsibility for damage,caused by or resulting from malfunction of the program,faulty copies or error in the manual are to be led back.

Copyrights and trademarks:

Amiga is a registered trademark of its owner.

Amiga, AmigaDOS, Kickstart and Workbench are trade-marks.

SAS and SAS / C are registered trademarks of the SAS Insti-tute Inc.

The designation of products which are not from the HAAGE& PARTNER COMPUTER GmbH serves information purpo-ses exclusively and presents no trademark abuse.

2 StormC - the professional choice

Page 3: StormC V3 Users Manual

Licensee agreement

LICENSEE AGREEMENT1 In general(1) Object of this contract is the use of computer programs from the HAAGE & PART-

NER COMPUTER GmbH, including the manual as well as other pertinent, writtenmaterial, subsequently summed up as the product.

(2) The HAAGE & PARTNER COMPUTER GmbH and/or the licensee indicated in theproduct are owners of all rights of the products and the trademarks.

2 Right of usufruct(1) The buyer does receive a non-transferable, non-exclusive right, to use the acquired

product on a single computer.

(2) In addition the user may produce one copy for security only.

(3) The buyer is not allowed, to expel the acquired product, to rent, to offer sub-licen-ses or in any other ways to put it at the disposal of other persons.

(4) It is forbidden to change the product, to modify or to re-assemble it. This prohibi-tion includes translating, changing, re-engineering and re-use of parts.

3 Warranty(1) The HAAGE & PARTNER COMPUTER GmbH guarantees that up to the point in

time of delivery, the data carriers are physically free of material and manufactu-ring defects and the product can be used as described in the documentation.

(2) Defects of the delivered product are removed by the supplier within a warrantyperiod of six months from delivery. This happens through free replacement or inthe form of an update, at the discretion of the supplier.

(3) The HAAGE & PARTNER COMPUTER GmbH does not guarantee that the productis suitable for the task anticipated by the customer. The HAAGE & PARTNERCOMPUTER GmbH does not take any responsibility for any damage that may becaused.

(4) The user is aware that under the present state of technology it is not possible tomanufacture faultless software.

4 Other(1) In this contract all rights and responsibilities of the contracting parties are regula-

ted. Other agreements do not exist. Changes are only accepted in written formand in reference to this contract and have to be signed by both parties.

(2) The jurisdiction for all quarrels over this contract is the court responsible at theseat of HAAGE & PARTNER COMPUTER GmbH

(3) If any single clause of these conditions should be at odds with the law or lose itslawfulness through a later circumstance, or should a gap in these conditionsappear, the unaffected terms will remain in effect. In lieu of an ineffective term ofthe contract or for the completion of the gap an appropriate agreement should beformulated which best approximates within the bounds of the law the one thatthe contracting parties had in mind as they agreed on this contract.

StormC User Manual 3

Page 4: StormC V3 Users Manual

P

REFACE

(4) Any violation of this licence agreement or of copyright and trademark rights willbe prosecuted under civil law.

(5) The installation of the software constitutes an agreement with these license condi-tions.

(6) If you should not agree with this license agreement you have to return the productto the supplier immediately.

June 1996Preface

4 StormC - the professional choice

Page 5: StormC V3 Users Manual

Preface

PREFACE“We develop to PowerUp the AMIGA.“Here it is at last - a new compiler system that gives you theability to develop powerful applications for the Amiga moreeasily, efficient and very fast. It is a completely newdevelopment system that gives you the tools you have beenmissing on the Amiga for a long time. New concepts and alook forwards into the future.

Some a 18 months ago we asked ourselves: why is there nodevelopment system for the Amiga that beats those of otherplatforms such as CodeWarrior (Macintosh) or BorlandC++.These programs make it so easy to create good programs. Sowe started to look for good people who could realise thisvision. After a short time we found them:

Jens Gelhar: He did the first C++ compiler for the Amiga in1992. Now he puts all his experience into the StormCcompiler.

Jochen Becher: He is one of the founders of HAAGE &PARTNER. He did his first compiler some years ago. Then heprogrammed a source-level debugger for a C++ compilerand one of the first C++ Class Libraries for the Amiga.

He is the Project Manager of StormC and he is the father ofStormShell and the project manager.

Michael Rock: He too has been programming on the Amigafor a long time. He is responsible for the very fast and verycompatible StormLINK - StormC’s linker. Now he isworking on the PowerPC code generation as well.

Besides these guys many others did a good job of suppor-ting StormC during development. There are assistantprogrammers, beta testers, many programmers using thedemo version and reporting their wishes to us and thecustomers who always encouraged us to do a little more ;-)

We released the International version of StormC to make itspower available to every Amiga programmer. Now it is upto you to “PowerUp the AMIGA“ with your fine programs.

We are now working on the next step towards the future:the PPC version of StormC for the new PowerAMIGA.

StormC User Manual 5

Page 6: StormC V3 Users Manual

P

REFACE

Now we want to thank our beta testers and all the peoplewho supported us during the development of StormC.

Thank you very much:

Olaf BarthelHolger BurkarthThomas BayenBernhard BüchterJan-Claas DirksMario KettenbergerAlexander PratschMichael RockJürgen SchildmannStephan SchüerholzThomas WilhelmiHeinz Wrobel

Special thanks to Jeroen T. Vermeulen.

Particular thanks goes to Gudrun Volkwein, BernadetteBecher and Hartwig Haage.

6 StormC - the professional choice

Page 7: StormC V3 Users Manual

Technical support

TECHNICAL SUPPORTIn case of problems concerning StormC you should:

1. Check your installation for completeness and read theReadMe file.

2. Check the installation of your operating system forcompleteness and verify that all relevant parts containthe right version numbers (at least OS 3.0).

3. Check programs that are running in the background.There might be some software running on your Amigathat will interfere with StormC. In particular sometools and patches, which are loaded in the Startupsequence, can considerably affect the mode of opera-tion. Try starting your Amiga without these programs,to be sure that they are not the cause of the trouble.

4. Please keep your Registration number handy.

5. Write down the version number of StormC (“About“window) and the version numbers and build dates ofcomponents (Storm.Library, StormC, StormCPP, Stor-mEd, StormLink, StormRun, StormShell). You getthem by typing the command

version “file name“ full

in CLI or Shell.

6. Please note your hardware and software configurationtoo.

7. If you think that your problem is caused by an error ofStormC then please try to narrow down the error tothe smallest possible piece of your code and send it tous (by mail or e-mail).

You can tell us your problems through many channels:

Internet: [email protected]

Contacting us by e-mail is most convenient to handle forus. We can forward your problems to the developers veryeasily. If you could send us a code segment containing theerror, this would certainly speed up the process of fixing the

StormC User Manual 7

Page 8: StormC V3 Users Manual

P

REFACE

bug tremendously. Via e-mail we can respond to yourmessage very easily or send you an individual patch oradvoice. Please use e-mail if at all possible.

WWW homepage: http://www.haage-partner.com

On our homepage on WWW on Internet you will find thecurrent information on StormC. Here we also have a specialsupport area with hints, patches, bug fixes and a lot ofinformation about StormC.

HAAGE & PARTNER Computer GmbHSchlossborner Weg 761479 GlashuettenGermany

Tel: ++49 - 61 74 - 96 61 28Fax: ++49 - 61 74 - 96 61 01

The Hotline is occupied from Monday through Friday from3:00pm to 7:00pm o’clock. Please be prepared with theinformation the support-staff members will need. This willspeed up the solution of your problems.

We prefer Support in writing because some problems can’tbe solved by phone, so we recommend the use of e-mail,fax or normal mail.

8 StormC - the professional choice

Page 9: StormC V3 Users Manual

Table of contents

COPYRIGHT 2STORMC C/C++ DEVELOPMENT SYSTEM 2

Licensee agreement 3

PREFACE 4Preface 5

“We develop to PowerUp the AMIGA.“ 5

Technical support 7

1 WELCOME 19AMIGA IS BACK FOR FUTURE. 19

If you don’t like manuals 19

If you are familiar with C and C++ 19

If you never worked with a compiler nor did any programming in C 20

2 INSTALLATION 21OVERVIEW 22

Before you install 22Localization 22

Installing with low memory 23

Full installation 24Novice User: 24Intermediate User: 24Expert User: 24

Selecting the installation directory 25

Installing an update 26

Removing StormC 26Custom files in the StormC drawer 27After Installation 27Troubleshooting the Installation 27Correct StormC installation 27

StormC User Manual 9

Page 10: StormC V3 Users Manual

T

ABLE

OF

CONTENTS

3 FIRST STEPS 29BEFORE YOU BEGIN 30

Running the program 30StormShell 30StormC 31StormLink 31StormEd 31StormRun 31StormASM 31

Toolbar access 32Keyboard control 32The icon bar offers the following functions: 32

THE CONCEPT OF PROJECTS 33The simple way 33

An easier approach through batch files 33

STORMC’S PROJECT MANAGEMENT 34

Creating a new project 34

What is a project? 35

Make and module dependencies 35

Saving the project and creating a new directory 35

Adding files to the project 37

Automatic Usage of Preferences 37

Specifying the program’s name 38

Saving the project 38

Creating a source file 39

Adjusting settings 40

Compiling the source code 40

Running the translated program 42

Console output 42

4 PROJECT MANAGER 45OVERVIEW 47

Some words about the startup 47

10 StormC - the professional choice

Page 11: StormC V3 Users Manual

Table of contents

Tooltypes 47The ScreenManager 48

Memory usage 51

Settings 51Automatic storage 52Automatic storage of unnamed files 53Automatic backup copy 53Selecting text font 53

ORGANISATION OF A PROJECT 55Creation of a new project 55

Setup of projects 56

Project Sections 56

Adding Files 57Adding Sources 58Add Window 58Adding Libraries 58Choosing a program name 59

Drag&Drop 59

Controls of the Project Window 59Folding of Sections 60Showing Sources 60Starting a Program 60Open a Child Project 61

Keyboard control 61Cursor keys 61Return 61

Deleting Items of a Project 61

Organising files of a project 61Project specific headers 62Documentation, scripts ... 63

Makescripts 63

Passing arguments to makescripts 66Assembler scripts 67

Saving of the paths 69

PROJECT SETTINGS 70Paths and global settings 70

Include path 71

StormC User Manual 11

Page 12: StormC V3 Users Manual

T

ABLE

OF

CONTENTS

Header Files 71Working memory - Workspace 72

Definitions and Warnings 72

ANSI-C/C++ Settings 74Source 74Template Functions 74Exceptions 75Debugger 76Code Generation 76Processor Specific Code Generation 77

Quality of the Optimisation 78Optimising 78

Compiler Warnings 80Standard of the language 80Security 81Optimisation 81

Path Settings and Linker Modes 82Generation of Programs 82Library Path 84Warnings 84Optimiser 84

Hunk Optimisations and Memory Settings 85Summarise Hunk 85Manner of Memory 86ROM Code 86

Call of the executable program 87Execute Environment 87Start From CLI 87I/O Settings 88Input/Output 89

Save Project 89

5 STORMED 91IN GENERAL 93

New text 93

Controls of windows 93

Open / Load Text 94Tooltypes 94

12 StormC - the professional choice

Page 13: StormC V3 Users Manual

Table of contents

Save Text / Save Text As ... 94

Free Text 94

Options of Text 95Tabulations and Indents 95Indent ahead and behind of brackets 96Dictionaries and Syntax 97Dictionaries 97Syntax 98Colour Settings 99File Saving Settings 99Saving the Settings 100

Keyboard Navigation 100Cursor-Keys 100<Return>, <Enter>, <Tab> 100

Undo / Redo 100

Block Operations 101Mark, Cut, Copy and Paste 101

The Mouse 102

Find and Replace 102Direction 103Mode 103Ignore Upper/Lower Case 103Ignore Accent 103Find 103Replace 104Replace All 104

6 COMPILER 105SPECIAL FEATURES OF STORMC 107

DATA in Registers 107

Parameters in Registers 108

Inline Functions 108

The Pragma instructions 110Data in Chip and Fast RAM 110AmigaOS Calls 111The #pragma tagcall 111

The #pragma priority 112Constructors and Destructors in ANSI C 113

StormC User Manual 13

Page 14: StormC V3 Users Manual

TABLE OF CONTENTS◆

Constructors and Destructors in C++ 113Priority list 113

Joining Lines 114

Predefined symbols 115

Build your own INIT_ and EXIT_ routines 117

Use of Shared libraries 117Prototypes 117Stub Functions 118#pragma amicall 118Forced opening of a Amiga library 122

PROGRAMMING OF SHARED LIBRARIES 123

The Setup of a Shared Library 123The #pragma Libbase 124Register Setup 124Shared Library Project Settings 125The setup of FD files 125The first four Functions 126Home-made Initialisation and Release 127Important hints to Shared libraries 128

PORTING FROM SAS/C TO STORMC 130Project settings 130

Syntax 131

Keywords 131

CLI VERSION OF THE COMPILER 134The instruction 134

Options 134Assembler source 136Pre-processor: Definition of symbols 136 Pre-processor: Include files 137

Compiler mode 137ANSI C or C++ 137Exception handling 137Creation of Template functions 138

Code creation 138Data model 138Code model 138

14 StormC - the professional choice

Page 15: StormC V3 Users Manual

Table of contents◆

Optimisations 138Code for special processor 140Code for linker libraries 141

Debugger 141RunShell 141Symbolic debugger 141

Copyrights 141

Warnings and errors 141Format of the error output 141Colours and styles 142Error file 142Optional warnings 143Treat warnings like errors 144Core memories 144Pre-compiled header files 144

Summary 145

7 THE DEBUGGER 149GENERAL INFORMATION

ON RUNSHELL 151The StormC Maxim 151

A Resource-Tracking Example 152

Freeze the program temporarily 153

Halting the program 154

Changing the task priority 154

Sending signals 154

USING THE DEBUGGER 157The Variable Window 159

Temporary Casts 161

Changing Values 161

Sorting of Variables 161

THE PROFILER 164Profiler technical information 167

REFERENCE 169

StormC User Manual 15

Page 16: StormC V3 Users Manual

TABLE OF CONTENTS◆

Control Window 169Status line 169“Program Stops At Breakpoint“: 169“Continue Program“: 169“Program waits for ...“: 169Debugger icons 169Go to next breakpoint 170Step in (single step) 170Step over (single step, but execute function calls without stopping) 171Go to the end of the function. 171Show Current Program Position 171Pause 172Kill 172Priority gadgets 172Signal group 172Protocol gadgets 172Window close gadget 173

Current variable window 174

The module window 177

The function window 178

The history window 178

The breakpoint window 179

The address requester 180

The hex editor 181Choosing the display 181The address string gadget 181The address column 181The hexadecimal column 181The ASCII column 181Keyboard control 182The scrollbar in the hex editor 182

8 THE LINKER 183THE LINKER,

THE UNKNOWN CREATURE 185A first example 185

ANSI-C Hello World 185

Startup Code 186

16 StormC - the professional choice

Page 17: StormC V3 Users Manual

Table of contents◆

Usage 189

Parameters 189

Memory classes 191

Compatibility 200

Error Messages 200

Error Messages 201Unknown symbol type 20116-bit Data reloc out of range 2018-bit data reloc out of range 201Hunk type not Code/Data/BSS 20116-bit code reloc out of range 2018-bit code reloc out of range 201Offset to data object is not 16-bit 201Offset to code object is not 16-bit 202Offset to data object is not 8-bit 202Offset to code object is not 8-bit 202Data- access to code 202Code- access to data 202InitModules() not used, but not empty 202CleanupModules() not used, but not empty 203File not found 203Unknown number format 203Symbol is not defined in this file 203Nothing loaded, thus no linking 203Can not write file 203Program is already linked 204Overlays not supported 204Hunk is unknown 204Program does not contain any code 204Symbol not defined 204Symbol renamed to _stub 204_stub is undefined 20532-Bit Reference for Symbol 20532-bit Reloc to Data 20532-bit Reloc to BSS 20532-bit Reloc to Code 20532 Bit Reference for symbol from FROMFILE to TOFILE 205Jump chain across hunk > 32 KByte not possible 205More than 32 KByte merged hunks 205Illegal access to Linker-defined Symbol 205Fatal errors : aborting 206Hunk_lib inside Library ?? 206Hunk_Lib not found 206

StormC User Manual 17

Page 18: StormC V3 Users Manual

TABLE OF CONTENTS◆

Wrong type in Library 206

Predefined values 206Symbols for data-data relocation 208Hunk Layout 208Memory Classes 208

Order of Searching for Symbols 209

Hunk Order 209

Near Code / Near Data 209

18 StormC - the professional choice

Page 19: StormC V3 Users Manual

Welcome1 ◆

1 Welcome

e thank you for buying this development system. Be assured that this wasthe right decision. StormC is the best tool to speed up your softwaredevelopment, to make it more comfortable and easy.

With StormC we give you a tool for the future of the Amiga. With the help of StormCyou can build applications of outstanding quality that help assure the persistence of theAmiga.

After working a while with StormC you will never understand how you ever did withoutit. We put all our experience into it and development is still going on. Next step is thePowerPC version for the PowerAmiga. Then you will be one of the first who’sapplications will run in PPC native code. And then

AMIGA IS BACK FOR FUTURE.

If you don’t like manuals Are you somebody who never reads a manual? So working with computers must beinborn. Congratulations!

In most cases there will be a problem that you can not solve on your own. You couldphone us to get the answer, but you can also have a look at the manual. If you are abeginner you should work through the basics. Read the first chapters about the editor,project manager, and compiler. Use the rest as a reference and work through it if youneed to. If you still have questions, you can contact us then. This will work best for allof us. :)

If you are familiar with C and C++ In this case you should have a look at the concepts of StormC. You will only will get thebest out of you programming system by knowing the details.

W

StormC User Manual 19

Page 20: StormC V3 Users Manual

1 WELCOME◆

If you never worked with a compiler nor did any programming in C Then StormC is best for you. One of our main goals was to design a development systemthat makes programming easier. So we did an integrated system where you don’t needto care about the individual parts. You simply type your source into the editor and thenhit “Run“ and the rest will be done by StormC: saving, compiling, linking, running. Werecommend that you try out “First Steps“. There you will get the basics of StormC. Lateryou should work through the first chapters of the manual: editor, project manager,compiler. Later you should read through the other chapters as well to get an overview ofthe possibilities of StormC.

20 StormC - the professional choice

Page 21: StormC V3 Users Manual

Installation2

StormC User Manual 21

◆2 Installation

his chapter describes how to install StormC on your hard disk. To avoidinstallation problems you should proceed the installation step by step asdescribed here.

OVERVIEW ....................................................................................................... 22

Before you install .......................................................................................... 22Localization ........................................................................................................ 22

Installing with low memory ..................................................................... 23

Full installation .............................................................................................. 24Novice User: ........................................................................................................ 24Intermediate User: .............................................................................................. 24Expert User: ........................................................................................................ 24

Selecting the installation directory ....................................................... 25

Installing an update ..................................................................................... 26

Removing StormC ......................................................................................... 26Custom files in the StormC drawer ..................................................................... 27After Installation ................................................................................................ 27Troubleshooting the Installation ........................................................................ 27Correct StormC installation ................................................................................ 27

T

Page 22: StormC V3 Users Manual

2 INSTALLATION◆

OVERVIEWTo guide you through the installation, Commodore’sInstaller will be used. It has become the standard applicationfor this purpose. You should have no problems using it.

Before you installStormC is shipped on a set of disks or a CD. Please put thefirst disk into your disk drive or the CD into your CD-ROMdrive.

You can find information on the memory

usage of the system in a file called “Readme“ on the disk. This file also contains information about recent changes since the manual was printed.

Before you install make sure that there’s enough space onyour hard disk for StormC. Otherwise the installation can beinterrupted.

After you insert the disk or the CD, double-click the drive’sicon, and a window similar to the following illustration isshown on your monitor.

LocalizationDepending on which language you prefer you can decidewhether the installation should occur in the German orEnglish language. This setting does not affect StormC’slocalization settings. Both choices offer you the possibility toinstall one or more localization catalogues.

22 StormC - the professional choice

Page 23: StormC V3 Users Manual

Installing with low memory◆

Starting the installationDouble-click one of the icons. Soon the installer’s window will open.

Installing with low memoryEven if there’s only a little space left on your hard disk youcan still install StormC. In this case run the Installer inExpert Mode. You will then be asked to confirm theinstallation of every part of the package.

The following components are required for StormC andshould be installed:

Include (dir) - all Includes except for the "Proto" and "Pragmas"

drawers Lib (dir)- Storm.lib - Amiga.lib

StormSYS (dir)- Appmanager.library- StormC - StormCPP - StormEd- StormEdGUI.wizard- StormLink- StormShell- StormShellGUI.wizard- (StormRun)- (StormRunGUI.wizard)

LIBS: (dir)- wizard.library

You don’t necessarily need to install the run time system andthe debugger. However this also gives you the possibility torun and debug your programs right out of the compilerenvironment.

You may of course leave off the entire environment andproceed with an even smaller installation. The StormSYSdrawer should then contain these programs:

StormSYS (dir)- StormC - StormLink

Normal Installer-Icon

Selected Installer-Icon

StormC Usermanual 23

Page 24: StormC V3 Users Manual

2 INSTALLATION◆

Full installationAfter starting, the installer’s window appears withinformation about its version number and date. At thebottom you can see two gadgets. Click on "Continue" andthe next page of the installation will appear where you canchoose settings concerning the installation process. A clickon "Abort installation" and answering "Yes" at the "Areyou sure?" prompt will quit the installation. These twogadgets will guide you on every page of the installationprocess.

The second page allows you to set parameters affecting theentire installation process.

If there is already an old installation on

your Amiga it will be replaced in novice mode without further information.

Novice User:In this mode everything is automated. After selecting thedrive to install to a complete installation will be performed.You will only be asked to change disks, if necessary.

Intermediate User:This mode gives you more control over the installation. Theinstaller detects a previously existing installation and asksyou if you want to reinstall from scratch, install an updateor remove the old installation.

Expert User:The expert mode gives you nearly full control over theinstallation. This is useful if you don’t want to install the fullpackage but just parts of it.

24 StormC - the professional choice

Page 25: StormC V3 Users Manual

Selecting the installation directory◆

Each time the installer is about to copy something you willbe shown a list of files. Only the files you select will actuallybe copied. Furthermore this page allows you to change thedestination path. This is, however, not advised, as it makeslittle sense. The complete installation, except for some toolsand configuration files, will be done in a single directory("Drive:StormC") and should not be spread aroundmanually to multiple directories.

This prompt only exists in the “Intermediate User“ and“Expert User“ modes, and only if there’s already an existinginstallation, including the first StormC Preview, and thecurrent demo versions. For more information refer to"Installing an Update" and "Removing StormC".

The installer will create a directory “StormC“ on the

selected drive or in the selected path. Diskette drives and the RAM disk are not allowed as destinations.

Selecting the installation directoryWhen installing from scratch you select a drive or directorywhere the StormC file will be stored.

After selecting the destination path, the file

"Readme" will be copied and displayed. You should read about recent changes since the manual was printed during the installation process.

Click on "Show drives" if you don’t want to install on thecurrently displayed drive, which is the default destination.Then click on a drive in the list shown.

Select "Create a new drawer" if you wish to create a newdrawer inside the directory currently shown. However, keepin mind that the installer will automatically create a“StormC“ drawer and copy all files there.

"Parent drawer" takes you one level back in the directorystructure.

StormC Usermanual 25

Page 26: StormC V3 Users Manual

2 INSTALLATION◆

Select "Continue" when the installation location is okay.

Depending on the user level chosen, the installation isperformed automatically. We do not recommend changingthe destination for parts of the package.

During an update, all files you modified

(e.g. includes, demos and preferences) will be over-written. You should therefore create a backup of your changes prior to updating and restore it afterwards.

Installing an updateThe installer automatically recognises if there’s already anexisting version of StormC on your hard disk. It will notifyyou (see the illustration on the previous page) and offer toreinstall from scratch, install an update or remove the oldinstallation completely.

When updating, you, of course, won’t be asked where toinstall since the old location is already known.

In “Novice User“ mode the old installation will beoverwritten without further inquiry.

In “Intermediate User“ mode the installer will check beforeunpacking whether the current file already exists andprompt whether it should be overwritten. With partsconsisting of multiple files the installer will not ask toreplace each file.

The “Expert User“ mode guarantees full control over theUpdate installation. Files will be temporarily unpacked intoRAM:, and you will then be asked for every single file to becopied.

Removing StormCWe regret if you wish to remove your StormC installationfrom your hard disk, but it will be mentioned here anyway.

Only files copied during the StormC

installation will be removed.

You will, of course, only have the possibility to remove theinstallation if the installer detects it.

Depending on the User level chosen, you will be asked foreach file whether or not you want to remove it.

As only a few files are required outside the StormC drawer, amanual deinstallation should be no problem. The icons forthe editor files and project management are removed fromthe "ENVARC:" and "ENV:" directories. The StormScreen-Manager is removed from your hard disk’s "WBStartup"drawer. Of course, the Assignment in your "User-Startup"

26 StormC - the professional choice

Page 27: StormC V3 Users Manual

Removing StormC◆

will be removed, otherwise you would get an error messageduring the next reboot of your system, that the drawer doesnot exist anymore.

Custom files in the StormC drawerOf course, StormC will not be removed if the Installer detectscustom files in it. You will be notified of this and need tomove these files somewhere else on your harddisk and deletethe "StormC" drawer yourself.

After InstallationIf you did not fill out the registration card yet this is the besttime to do so. You should by all means register so that we caninform you regularly about updates and upgrades.

Troubleshooting the InstallationIf you have followed the listed instructions, you should haveno problems during the installation. It is, however,impossible to predict when a file or even a complete disk isdamaged. If only one, or just a few files are damaged, theinstallation may be performed manually.

Please inform us as soon as possible about the damage. Wewill then send you a replacement disk.

To allow you to continue working with the compiler systemthe following list gives you information about the files andtheir required location.

Correct StormC installationOn the first StormC disk you can find a list of the files of acomplete StormC installation.

StormC Usermanual 27

Page 28: StormC V3 Users Manual

2 INSTALLATION◆

28 StormC - the professional choice

Page 29: StormC V3 Users Manual

First Steps3

StormC User Manual 29

◆3 First Steps

very C-compiler’s introduction begins with the “Hello World“ program, sowill we.

With this simple example we want to show you the first steps you are waiting for. You will learn how to create a simple project, to write new source, to run the compiler, and, finally, to run the program.

BEFORE YOU BEGIN ................................................................................... 30

Running the program .................................................................................. 30

Toolbar access ................................................................................................. 32Keyboard control ................................................................................................ 32The icon bar offers the following functions: ........................................................ 32

THE CONCEPT OF PROJECTS ............................................................... 33

The simple way ............................................................................................... 33

An easier approach through batch files .............................................. 33

STORMC’S PROJECT MANAGEMENT ........................................................ 34

Creating a new project ............................................................................... 34

What is a project? ......................................................................................... 35

Make and module dependencies ............................................................. 35

Saving the project and creating a new directory ............................ 35

Adding files to the project ........................................................................ 37

Automatic Usage of Preferences ............................................................. 37

Specifying the program’s name .............................................................. 38

Saving the project ......................................................................................... 38

Creating a source file ................................................................................... 39

Adjusting settings ......................................................................................... 40

Compiling the source code ........................................................................ 40

Running the translated program ........................................................... 42

Console output ............................................................................................... 42

E

Page 30: StormC V3 Users Manual

3 FIRST STEPS◆

BEFORE YOU BEGINThe following instructions assume that you havesuccessfully installed StormC and rebooted your system. Ifyou didn’t, please go back and read Chapter 2: Installation.

Running the programPlease start StormC with a double-click on its icon (see themarginal illustration). You can find the icon in the drawerin which you installed StormC.

After starting, you will see a Welcome message whichremains until all of StormC’s components are loaded. If yourWorkbench has more than 32 colours you will see aWelcome picture as shown below.

The following programs, which belong to the compilerenvironment, will be run:

StormShellThe StormShell unifies the different parts of the compilerenvironment. It is responsible for important jobs such asproject management, without which programs consisting ofmultiple modules would not be possible.

30 StormC - the professional choise

Page 31: StormC V3 Users Manual

Running the program◆

Due to the integration in the compiler

environment you won’t notice that it consists of multiple programs. The communication between the parts occurs using an ARexx port which, as another benefit, offers very flexible interfaces to other programs.

StormCThe compiler is the heart of the StormC developingenvironment. The compiler accepts both ANSI-C and C++sources and performs optimisations as well. It supportscurrent ANSI standards and all features of the AT&T version3.0 compiler systems (CFRONT).

StormLinkThis amazingly fast linker is the interface to other compilersystems. It is able to process link libraries from the SAS/C andMaxonC++ compiler environments. This feature allows youto use all common libraries in your programs.

StormEdWe are sure that you will soon appreciate our editor’s twomajor features. Colorization of strings, comments, constantsetc. helps you to quickly and efficiently locate and removebugs. The included lexicon covers all functions and structurenames used on the Amiga. Because of the colorization youwill notice immediately whether an entered function nameis correct.

Another feature is the Editor’s usage for debugging purposes.When you start the debugger, already open windows andfunctions will be reused. You can continue working with theEditor as usual. Only the breakpoint column at the left andthe brightly rendered display of the program counter willremind you that you’re currently debugging your program.

StormRunStormRun contains the Source-Level-Debugger and the codenecessary to allow your programs to run from within thedevelopment environment. It is also responsible forResource Tracking.

StormASMStormASM is not a complete Assembler, but an interface toan external Assembler, PhxAss. Its demo version anddocumentation are included.

StormC’s major controls will be displayed as soon as it isloaded. The icons allow for access to the compiler’s mostimportant functions.

StormC User Manual 31

Page 32: StormC V3 Users Manual

3 FIRST STEPS◆

Some “Sun-Mouse tools“ may cause

problems when the help line is rendered. To fix this bug we have supplied the program “MagicMenuFix“. During the installation you will be asked whether you wish to install it in your WBStartup drawer. Refer to the “Readme“ file for more information.

Toolbar accessTheir accessibility through the icon window makes thesefunctions instantly available. A single click on an icon isenough to cause the associated function to be executed. Asyou have certainly already noticed a help line gives youdetails about these functions.

This feature is particularly important when you are justbeginning to use StormC. You will soon ignore the help linemore often and remember the functions associated with theicons. You will find the help also in other parts of theenvironment where icons are used.

Keyboard controlThe icon’s functions are also accessible using the functionkeys. <F1>-<F3> are used for the text functions, <F4>-<F6>for the project functions and <F8>-<F10> for the compilerand debugger functions.

The icon bar offers the following functions:

New sourcewindowLoad source

Save source

Make and debugMake and run

Make

New projectLoad project

Save project

Helpline

32 StormC - the professional choise

Page 33: StormC V3 Users Manual

The simple way◆

THE CONCEPT OF PROJECTSBefore we start writing and compiling source code I’d like todiscuss some basic aspects of writing programs.

The simple wayWith a “traditional“ compiler system you would start a texteditor, enter the source code, save it and run the compiler.Additionally, you would perhaps also specify extra options,or use the default settings, perhaps kept in an environmentvariable.

The compiler would then create an object file, and youwould run the Linker to get an Executable. Finished!

An easier approach through batch filesIt would be easier if you created a batch file containing thecommands you previously entered manually. After a changeto the source code you’d then only need to run the batch file.

This ease would be clearly perceptible, which results inhigher turn-around times and thus in a higher programmingefficiency.

This approach has no disadvantages as long as you’re onlyworking with a single source file. As soon as you integratetwo or more source files into the batch file, every time youcall it you would have all source files compiled - regardlessof whether a source file has been changed or not.

Thus, the turn-around times would always stay the same.With some little expense it would be possible to checkwhether a source file is newer than its associated object filebut that would be all you could do in a justifiable amount oftime.

Another major aid in this case is a so-called Make programwhich only passes modified source files to the compiler andalso supports dependencies. For details about Make refer tochapter 4 for a more intensive discussion.

StormC User Manual 33

Page 34: StormC V3 Users Manual

3 FIRST STEPS◆

StormC basically works with projects. Source

files can only be compiled when they’re part of a project. Read the following introduction step by step and you will learn about the simple usage of projects.

STORMC’S PROJECT MANAGEMENTSimilar to batch files, a StormC project contains a list of filesand settings. This is, however, created visually, which makesit easier to use and to understand. A StormC projects unifiesall parts belonging to a program so that they can be managedcentrally. This includes files which do not don’t directlyaffect the creation of a program, such as AmigaGuidedocuments, and ARexx and Installer scripts.

The project manager has similar properties to a Makeprogram and reacts accordingly when multiple source filesare used. Dependencies between source files and header filesare also no problem.

Creating a new projectThe most important step to compile a source file usingStormC is to create a new project. Source files can’t becompiled without being associated with a project. This mayappear to be a limit at first, but will save you a lot of troublelater on. Creating a project is really simple and helps to keepyour programming efforts ordered.

Please click on "New project" in the icon bar. A new projectwindow will be displayed.

34 StormC - the professional choise

Page 35: StormC V3 Users Manual

What is a project?◆

The illustration next to this text shows a new

project created by a simple click on the "New project" icon. The project’s preferences can be modified freely and saved as default settings for new projects.

What is a project?A project unifies everything belonging to your program: C,C++ and Assembler source files, header and object files, linklibraries, documentation, graphics, pictures and otherresources. The collection remains easy to manage throughseparation into different sections. The project manager is,however, also a visually orientated Make.

Make and module dependenciesAt every compiler run, the dependencies between ".o",".h", ".ass", ".asm", ".i" and ".c" files (of course also".cc" or ".cpp") will be evaluated and passed to the projectmanager. This allows the project manager to know that a Csource file needs to be recompiled when a ".h" header filehas changed that is being included in the ".c" source.

When you click on "Make", "Run" or "Debug" alldependencies will be checked, and Make decides whichprogram modules need to be recompiled and which do not.The only difference between "Run" and "Make" is that"Run," after successful compilation, automatically runs theprogram. Selecting "Debug" will automatically start theDebugger after compilation.

Saving the project and creating a new directoryBefore starting the next step, please save the project andcreate a new directory for it.

Please click on the "Save project" icon. In the displayedstandard ASL file requester please choose the "StormC:"directory and enter as file name "Hello World/HelloWorld".

StormC User Manual 35

Page 36: StormC V3 Users Manual

3 FIRST STEPS◆

The ".¶" suffix can also be entered manually

by pressing <ALT>+<P>.

The ".¶" suffix is automatically appended and signifies thatthis file is a StormC project.

When you have entered the file name as shown above intothe text gadget and pressed <Return>, you will be asked if youwant to create a new drawer. In order to keep a betteroverview you should create a new directory for every projectand proceed as shown.

After confirmation of the "create a new drawer"requester, you can click the "OK" gadget in the ASL filerequester and your project will be saved in the new directory.

You may wonder why the empty project needs to be saved;even if the project is empty it is recommended to specify aclear project path at the start. The names of the source filesand other resources can then be integrated and saved relativeto the project’s path (otherwise the absolute path would beused). Another advantage is that when adding new files tothe project the ASL file requester already contains theproject’s path, so you won’t have to enter it manually.

36 StormC - the professional choise

Page 37: StormC V3 Users Manual

Adding files to the project◆

Adding files to the projectWhen adding empty source files created with

"Add file(s)" the appropiate preferences for the given suffix will be taken from the preference icons located in the ENV: location.

To continue, please choose "Add file(s)" from the"Project" menu. Then enter "Hello World.cpp" as thefilename. The suffix should be usable to distinguish betweenANSI-C, C++ and Assembler source files and header files. Inour example we chose ".cpp" because we want to write a"Hello World" example in C++.

This illustration shows the ASL filerequester

where existing files may be selected and new files can be created. Please activate the “File“ text entry field with the mouse and enter “Hello World.cpp“ as file name.

Automatic Usage of PreferencesWhen you create a new file for use in the project, the file’spreferences will be taken from the preference iconsaccording to the specified suffix.

In our example the properties for the new source file "HelloWorld.cpp" are taken from the preference icon"ENV:STORMC/def_text.cpp.info". For files ending in".c" the properties would be taken from "ENV:STORMC/def_text.c.info" etc.

Of course you can modify and set the preferences to yourneeds. The icon’s tooltypes contain all settings made in the"Editor" and "Text" sections. You can access these in the"Settings" menu.

StormC User Manual 37

Page 38: StormC V3 Users Manual

3 FIRST STEPS◆

To save the modified settings use "Save As Default Icon"in the "Project" menu. You will be asked whether you wishto save the settings to the icon with the settings for theappropriate suffix or to "ENV:STORMC/def_text.info",which is responsible for the global settings.

Specifying the program’s nameWe will now specify the program name to be used by theLinker. If a project does not contain one it will create aprogram named "a.out" - if you link it at all.

When using the Debugger additional files

ending in ".debug" will be created for every source file. In order to inform the Debugger of which modules the program consists of, a file ending in ".link" will be created. If you have chosen a different path for the program than the project path, this ".link" file will be created there, too.

Please choose "Select Executable…" from the "Project"menu.

The displayed file requester will show the contents of theproject’s path. You can enter a file name in this path orchange it to suit your needs.

Saving the projectNext is an introduction to the text editor. Before proceeding,you should save the project again. Since the last time yousaved, you have followed the steps "Adding files to theproject" including creating a new drawer and "Specifying

38 StormC - the professional choise

Page 39: StormC V3 Users Manual

Creating a source file◆

the program’s name". Though it would not be very tragic,it would be annoying if these steps were destroyed bysomething unpredictable such as power failures etc.

To save the project just click on "Save project" or press thefunction key <F6>.

Creating a source fileWe will now proceed to the real programming. Open thepreviously created source file by double-clicking its name inthe project.

An empty editor window with the title "Hello World.cpp"will appear. Before you begin to enter text please have aquick look at the editor’s controls. This illustration may helpyou.

Please enter the following lines:// Hello World// Example program belonging to the// introductionary tutorial

#inklude <iostream.h>void main(){

cout << "Hello World" << endl;}

Save this text by clicking on the "Save text" icon in the toolbar.

Show end of lineShow tabs

Show spacesAutoindent

OverwriteLock editor

Show textchangesLine-/Column

StormC User Manual 39

Page 40: StormC V3 Users Manual

3 FIRST STEPS◆

Adjusting settingsBefore we compile the program please make sure that thecompiler’s settings are correct. Please choose the entry"Compiler…" out of the "Settings" menu. The windowfound in the illustration below will appear. If you open it forthe first time your window will look slightly different thanshown below.

Because the project settings could not be placed in a singlewindow we have divided and separated them onto differentpages.

At the upper border of the window you can find a paginggadget. With clicks you can browse between the differentsettings pages.

Please select the "C/C++ Options" page.

Make sure that the cycle gadget in the "Language" groupshows "C++". All other settings should be set as shown in theillustration.

Confirm these settings by clicking on "Use" or press the <U>key.

Compiling the source codeClicking "Make" will open the error window and the sourcecode will be passed to the Compiler. The compiler and the

40 StormC - the professional choise

Page 41: StormC V3 Users Manual

Compiling the source code◆

linker will output status and progress reports in the errorwindow.

If the compiler finds an error it will be reported in the displaybelow. You will find a very detailed error description, theline number, and the source file where the error was found.

In our example we intentionally made a mistake in line 1.Instead of #include we wrote #inklude. This is a very sillymistake you should have noticed when you entered the text.If you have colorization enabled in the editor the word#include will be rendered in a special colour. As soon as youchange only a single character, the color changes to thestandard color which is usually black. This allows you to findcareless mistakes while entering your text, and avoidsunnecessary compiler runs.

To demonstrate the error window, this simple mistakeshould be included in the source. As soon as the compilerfinds the mistake the appropriate error message is shown inthe window.

Of course a double-click on the error message is enough tocause the project manager to load the source code and showthe error line in the Editor. You can then correct it and runthe compiler again.

StormC User Manual 41

Page 42: StormC V3 Users Manual

3 FIRST STEPS◆

Running the translated programAfter successful compilation and linking you can click on the"Run" button (which was previously ghosted) or the "Run"icon to start the program. You can also press the functionkey <F9> instead.

If you click on the "Run" (<F9>) instead of the "Make"(<F8>) icon the project manager first checks whether allmodules have been compiled. If not, the compiler will be runfor all untranslated modules. After successful translation theprogram will be automatically run.

Console outputIf you have already started the program you will havenoticed that the program’s output could only be seen for ashort while, and disappeared almost immediately. Theprogram is very short and thus runs very fast. To see theoutput window also after the program has finished we needto specify the "x/y/width/height/title/options"parameters when opening the console.

Please open the project settings once again by selecting themenu item "Settings/Program Start…".

42 StormC - the professional choise

Page 43: StormC V3 Users Manual

Console output◆

In the second page of the window you can choose settingsregarding the in- and output. Please enter the following linein the "Console" text field:

Double-clicking the program’s name in the

project is sufficient to re-run the program.

CON://320/200/Hello World/CLOSE/AUTO/WAIT

Please restart the program by double-clicking the program’sname in the project.

The program will still be executed very fast but keep theconsole window opened. Close it by clicking the window’sclose gadget.

StormC User Manual 43

Page 44: StormC V3 Users Manual

3 FIRST STEPS◆

44 StormC - the professional choise

Page 45: StormC V3 Users Manual

Project Manager4 ◆

4 Project Manager

s you have worked through the beginning tutorials, you have heard aboutthe project manager. This is something new to Amiga compiler systems, butit is a common thing on other computer systems such as the Macintosh or

IBM PCs.

One of the goals of the development environment is to make work easier and moreefficient. The project manager is a big step in this direction.

If you look at traditional development environments, you will recognise that every effortwas made to build tools around the compiler, because it was the "heart" of the system.Nowadays, this has changed. The "heart" of the system is the project manager. Itassembles all parts of a project, and it navigates and controls every part of it.

The following chapter will tell you more about the project manager, how it works, howto configure it, and how to navigate throughout the development system with it.

OVERVIEW ....................................................................................................... 47

Some words about the startup ................................................................ 47Memory usage ................................................................................................ 51Settings ............................................................................................................. 51

ORGANISATION OF A PROJECT ..................................................................... 55

Creation of a new project .......................................................................... 55Setup of projects ........................................................................................... 56Project Sections .............................................................................................. 56Adding Files ..................................................................................................... 57

Adding Sources ................................................................................................... 58Add Window ....................................................................................................... 58Adding Libraries ................................................................................................. 58Choosing a program name ................................................................................ 59

Drag&Drop ....................................................................................................... 59Controls of the Project Window ............................................................. 59

Folding of Sections ............................................................................................. 60Showing Sources ................................................................................................. 60Starting a Program ............................................................................................ 60Open a Child Project .......................................................................................... 61

Keyboard control ........................................................................................... 61Cursor keys ......................................................................................................... 61Return ................................................................................................................. 61

A

StormC User Manual 45

Page 46: StormC V3 Users Manual

4 PROJECT MANAGER◆

Deleting Items of a Project ........................................................................ 61Organising files of a project ..................................................................... 61Makescripts ...................................................................................................... 63Passing arguments to makescripts ........................................................ 66Saving of the paths .................................................................................... 69

PROJECT SETTINGS ............................................................................................ 70

Paths and global settings ........................................................................... 70Include path ....................................................................................................... 71Header Files ........................................................................................................ 71Working memory - Workspace ............................................................................ 72

Definitions and Warnings .......................................................................... 72ANSI-C/C++ Settings ..................................................................................... 74

Source ................................................................................................................. 74Template Functions ............................................................................................. 74Exceptions ........................................................................................................... 75Debugger ............................................................................................................ 76Code Generation ................................................................................................. 76Processor Specific Code Generation .................................................................... 77

Quality of the Optimisation ...................................................................... 78Optimising .......................................................................................................... 78

Compiler Warnings ....................................................................................... 80Standard of the language ................................................................................... 80Security ............................................................................................................... 81Optimisation ....................................................................................................... 81

Path Settings and Linker Modes ............................................................. 82Generation of Programs ..................................................................................... 82Library Path ........................................................................................................ 84Warnings ............................................................................................................ 84Optimiser ............................................................................................................ 84

Hunk Optimisations and Memory Settings ......................................... 85Summarise Hunk ................................................................................................. 85Manner of Memory ............................................................................................. 86ROM Code .......................................................................................................... 86

Call of the executable program ............................................................... 87Execute Environment .......................................................................................... 87Start From CLI .................................................................................................... 87I/O Settings ......................................................................................................... 88Input/Output ...................................................................................................... 89

Save Project ...................................................................................................... 89

46 StormC - the professional choice

Page 47: StormC V3 Users Manual

Some words about the startup◆

OVERVIEWBefore we start with the project manager, I will tell you somebasics of the system. One point will be a precise descriptionof the start of StormC. You will certainly already have startedthe system, but the understanding of what happened andthe function of the controls may still not be clear.

You have launched the development system, but the itsbehaviour and the settings to be made are still open and aresubject to change.

Some words about the startupThe system is started by a program called StormCPP. This isa loader and its only duty is to start the other parts: StormC,StormED, StormLink, StormRun, StormASM and StormShell.As this could take a little while, a nice startup picture will beshown (if you are running an Amiga with less than 32colours on the Workbench screen, there will only be a smallwindow that shows you the progress.).

Default SettingAfter the installation of StormScreenManager, a public screen named "StormC" will be defined, but it will not be used. You have to activate the corresponding attribute in the tooltypes of StormCPP. Please open the information window and delete the round brackets at the beginning and the end of the corresponding line to activate this attribute. At the next startup of StormC, this screen will be opened automatically.Now the Tooltypes (of the StormCPP icon) will be executed (if possible). The following options can be used:

On an Amiga System with less than 32 colours onworkbench screen, a little window opens to tell you thedifferent programs being loaded.

TooltypesThe attributes of a program will be stored in its icon. Tochange it please click on the icon "StormCPP" and selectthe menu item "Icon/Information". The followingrequester will open.

StormC User Manual 47

Page 48: StormC V3 Users Manual

4 PROJECT MANAGER◆

QUIET The QUIET tooltype will disable the picture show at start.

The progress window which opens on Workbench screenswith fewer colours (when not enough colours are availableto show the pictures) will also be disabled.

HOTHELP Upon activating the editor window you can press the<HELP> key to get context sensitive help from theAmigaGuide docs. If you would like to have the program"HOTHELP" doing this job you must enter the tooltypeHOTHELP.

SAVEMEM When memory is low, the use of this tooltype offers thepossibility to only load parts of the system, to save memory.SAVEMEM prevents the loading of StormC, StormLink,StormASM and StormRUN. These parts are only loaded whenthey are needed. After beeing loaded these parts will stay inmemory as long as there is enough memory.

GOLDED The popular editor GoldED can be used instead of StormED.It is loaded form the drawer "GOLDED:". As GoldED is usedthe same way as StormED, it is not the control office of thesystem, so it must be loaded memory resident.

Please configure GoldED at "Config/Various..." setting"Various" to "resident" and save the settings.

PUBSCREEN With the PUBSCREEN tooltype, you can set the publicscreen name upon which all StormC windows will beopened. Like the Workbench, the public screen is sharedamong all programs and can be used as a target screen foranother application.

The creation of public screens is handled by a program thatis independent of StormC and which is started separately.During installation process, if you have allowed theinstallation of StormScreenManager, a little program iscopied in your WBStartup drawer to do this job.

The ScreenManagerThe StormScreenManager is a little commodity which will beautomatically started after each reboot. It will wait onbackground a public screen request and will react upon sucha call

48 StormC - the professional choice

Page 49: StormC V3 Users Manual

Tooltypes◆

After the StormC installation process, you have

to reboot your system in order to be able to use the StormScreenManager. To bring up its window, press the hotkey <Control>+<Alt>+<s>.

Of course, the StormScreenManager must know the namesand the settings of the screens to open. Otherwise, the publicscreen requests will be ignored and StormC and every otherprogram which asks for a public screen, will open theirwindows on the Workbench.

You can define your own hotkey definition to

bring up the StormScreenManager window by modifying the appropriate tooltype. Please refer to the Commodities chapter of your Amiga Workbench user manual.

An entry for StormC is already defined in theStormScreenManager. To use this public screen, you justhave to remove the parentheses on the same name entry inthe StormCPP icon tooltypes.

To do this, click once on the StormCPP icon and select themenu item "Information..." on the "Icon" menu of theWorkbench screen. Once you have the Information window,click on the PUBSCREEN tooltype, the string gadget will befilled with this tooltype. Then, you can remove theparentheses and press return to validate the changes. Youcan now start the development system by double clickingthis icon.

Now a new screen is opened and all the StormC programwindows will be shown there.

To modify the screen settings, you have to bring up theStormScreenManager window. Press <Control Alt s> and thewindow will popup as shown on the previous page.

Choose the StormC entry to modify its definitions. Thename will be displayed in the string gadget and can be edited

StormC User Manual 49

Page 50: StormC V3 Users Manual

4 PROJECT MANAGER◆

there. To change the screen mode, click on the "ModeID"gadget.

Choose the appropriate screen mode and depth for yourmonitor. Please, keep in mind that a minimum of 16 coloursare needed for the StormC screen. When using 8 or fewercolours, the editor can not correctly display the text in thepredefined colours.

On the right side of the StormScreenManager window, you’llfind some other gadgets.

New Creates a new standard entry in the public screen list. Theentry will be appended at the bottom of the list, and you canmodify the name in the string gadget and modify the othersettings with the appropriate gadgets like ModeID and Font.You can also open and close it right away.

Open Opens the selected screen in the public screen list. Screensalready opened (ie: The Workbench screen) may not beopened again.

Font Opens an ASL font requester for you to choose the font foryour screen.

Close Closes a screen opened by the StormScreenManager.

Delete Closes a screen opened by the StormScreenManager andremoves its entry in the public screens list.

In order to save all the changes applied to all the screens youhave defined, you must select the menu item "Save" in the"Project" menu of StormScreenManager.

50 StormC - the professional choice

Page 51: StormC V3 Users Manual

Memory usage◆

To finish with the screen manager a single click on thewindow close gadget will hide it. This will only close theprogram window and this is the equivalent of the "Hide"menu item of the "Project" menu. If you want to deactivatethe program as well as remove it from memory you mustselect the "Quit" menu item in the "Project" menu.

Memory usageWhenever starting the StormC development system, italways tries to load as many program parts as possible inmemory to make them resident modules

If you are low on memory, StormC will still try to start up ifthere’s enough memory to start StormShell and StormED

The programs StormC, StormLink and StormRun will bestarted via a Shell for any compilation and will be unloadedafterwards. This way, turnaround times will be higher.

SettingsBefore opening any project or source, fundamental systemsettings should be created and saved.

Following settings can be made:

HexEditorThe initial size, position, display, and start address to showin the HexEditor window within the debugger can be sethere.

Source text editorWhen the ProjectManager is in the "empty" state, you can setthe font and paths for the source text editor. The othersettings, such as syntax colourisation and entries linked withsource files, will be saved in the predifined icon. Moreinformation about this later.

StormC User Manual 51

Page 52: StormC V3 Users Manual

4 PROJECT MANAGER◆

Menu item names followed by 3 points (i.e.:

"...") indicate that this is not a direct function, but that more information is needed such as a confirmation or special settings. A good example is the menu items "Save" and "Save As...". Selecting "Save" will save the file immediately. "Save As..." will let you change the name before performing the "Save" function.

Selecting the menu item "Settings/Editor...", thefollowing requester will pops up.

This window can be sub-divided in order to separately definethe File, Font and Colour settings.

The upper paging gadget lets you swap between the File,Font and Colour settings.

The picture above shows the file settings editor. This iswhere you can define the AutoSave settings and if you wantto keep backups of your source files.

Automatic storageWith the cycle gadget within the "AutoSave" group, youcan swap between the following possibilities.

Never There will not be any automatic storage.

Into original file At this position the storage will be done overwriting theoriginal file. The flag indicating file changes will be removedonce the storage procedure has completed successfully.

Into extra file If the automatic storage is to be done in an extra file, asecond file will be created with the suffix ";0". The AutoSavewill still be performed in the same file.

The "M" flag will not be changed. It means that the securefile will be more recent than the original file after a possiblecrash. After a restart, if you load your original source, a

52 StormC - the professional choice

Page 53: StormC V3 Users Manual

Settings◆

requester will pop up to tell you that the AutoSave file ismore recent than your original file.

Automatic storage of unnamed filesIf a file is still unnamed at the automatic storage timeout, arequester will pop up to give you the chance to enter a name.

An ASL filerequester will let you enter a name for this file. Ifyou cancel the ASL requester, it will pop up again after theAutoSave timeout.

Automatic storage will only be performed if the text hasreally been modified. Of course, whether any changes havebeen made can be seen by the "M" flag in the status bar ofevery window.

If you have checked the "Confirm AutoSave" gadget, arequester will ask confirmation before saving the file.

Automatic backup copyIf you have checked the "Make backups" gadget in the"Backup" group, as many copies as selected will beperformed. The files will have the suffix ";1" to ";9"depending on the selected copies number.

For instance, setting the number of backup copies to 2, thefirst time a file is saved (manually or automatically) willrename the original. It will have the ";1" suffix and a neworiginal file will be created. The next time that file is saved,the file with suffix ";1" will renamed with the suffix ";2". Theoriginal file, as before, will be renamed with suffix ";1". Anew original file will be created. The third time, it will reactexactly as described before.

Selecting text fontIn the general editor settings window, choose the "Font"position for the paging gadget.

StormC User Manual 53

Page 54: StormC V3 Users Manual

4 PROJECT MANAGER◆

The font selected here will be used for all the editor windows.With the cycle gadget in the "Text font" group, you canchoose between the screen font and a custom font.

The default settings of StormC will use the screen font. Thisis the font you selected with the font preferences of theWorkbench for "Default text font".

The editor window can only display properly

with monospaced fonts. This means that only non-proportional fonts (where the width of all the characters is the same) may be used.

Clicking on the cycle gadget until "Custom font" is shown,will let you select the font and its size.

Clicking on the pop up gadget to the right of the stringgadget will pop up an ASL font requester to choose the fontand its size. This requester will only display the non-proportional fonts.

A detailed description of the use of the ASL font requestercan be found in your AmigaDOS user manual.

54 StormC - the professional choice

Page 55: StormC V3 Users Manual

Creation of a new project◆

ORGANISATION OF A PROJECT

Each program you create with StormC should be defined asa project. All projects contain at least the source, allpertinent header files, the name of the program to be createdand the options for the compiler, linker and debugger.

Moreover you can add ARexx and Installer scripts,documentation as ASCII or AmigaGuide files, and otherprogram related files to your project.

Creation of a new projectTo create a new (empty) project you have to click on the icon"New Project" in the Toolbar. When the Toolbar isactivated you can select the menu item "New" from"Project" as well.

If there is no file "template.¶" in "PROGDIR:"

StormC uses its default settings for the new project. In this case the project will not contain any settings for standard libraries and an error message will not be created.

The default settings for a new project will be loaded from thefile "template.¶" which can be found in "PROGDIR:"which is the drawer StormC was started from. If you have notchanged the installation (which you should not do), it is thedrawer "StormC:StormSYS".

The template of the project contains predefined options forthe compiler, linker, debugger, and the standard libraries.

Of course you have the option of changing all defaultsettings, so when creating a new project your preferredsettings will be used. More information on the definition ofproject templates can be found in the "Own Project -Template" section of this chapter.

StormC User Manual 55

Page 56: StormC V3 Users Manual

4 PROJECT MANAGER◆

Setup of projectsWhen creating a new project,a new project window appearson the screen in which the standard libraries can be found.

Horizontally the project divides into three sections:

File The horizontal section "file" shows, as the first entry, thetitle of the vertical section. In our example it is the section"Libraries". In front of the title you can see a small trianglewhich points to the bottom. The triangle symbolises thatthis section is not folded so the following entries up to theseparating vertical line are part of the "Libraries" section.In our example the names of the libraries are "Storm.Lib"and "Amiga.Lib".

Code On the right beside the file section there is a code sizesection. Here you will find the size of the output code ofcompiled or assembled sources, linked programs andlibraries. This section remains empty for header or other fileswhich are not translated by the compiler.

Text On the right side of the window you will find the text size ofscript files (e.g. ARexx and Installer scripts) or other ASCIIfiles. In our example this section is empty because these arelibraries without source, so their size is unknown.

Project SectionsIf there were no project sections all data of a project wouldbe disorderly. You would only recognise the meaning of afile by its extension, it it had one. To get a better idea ofwhich files are which, we included the project sections.

56 StormC - the professional choice

Page 57: StormC V3 Users Manual

Adding Files◆

In this picture you will see all possible project sections, but more could be added in the future.

All project sections start with a title. The following picture ofthe project sections contains the section "Libraries" at first.So all following lines (it is only one in this case) are librarieswhich should be used by the linker.

Adding FilesThere are various ways to add a file to a project. The normalway is to use the menu item "Project/Add File(s)". As youwill see there are four entries that deal with this matter.

Sections Objectcode size Sourcecode size

Folding switcher.Use the mouse orthe return key toopen and closethe section.

StormC User Manual 57

Page 58: StormC V3 Users Manual

4 PROJECT MANAGER◆

Adding SourcesSources are all ASCII files of the project. A fine distinctionwill be made by the file extension.

When choosing the menu item "Project/Add File(s)," youwill have the option of selecting one or more files to add toyour project. The ASL filerequester is used for this.

A description of the usage of the ASL filerequester

can be found in your Amiga manual.

When choosing several items at a time, they will be insertedalphabetically. If you would like to have them in anotherorder you must select them individually.

Add WindowThe menu item "Project/Add Window" is available onlyif there is an active editor window. Choosing this item willadd the filename of the text of the activated editor windowto the project.

If you didn’t gave a name to your text file before this, youwill get the opportunity to do it now.

Adding LibrariesTo make adding of libraries easier, there is a special menuitem called "Project/Add Librarie(s)". The ASLfilerequester will come up with the library path you selectedin project settings so you can add libraries very quickly.

58 StormC - the professional choice

Page 59: StormC V3 Users Manual

Drag&Drop◆

Instead of using the normal linker libraries you can

use the MaxonC++ compatible manner of using a logfile for linking. Please note that the logfile will be used after the normal linking. If you are using normal libraries as well, they will be linked first and then the logfile will be executed.

Please note that if you are using multi-selection this list will be inserted alphabetically. That means that "Amiga.Lib" will be linked before "Storm.Lib" which could cause trouble

It is important to know that "Amiga.Lib" containsfunctions with the same names as functions in the standardANSI library, but there are differences in the parameters.When linking "Amgia.Lib" before "Storm.Lib," thesefunctions will be taken from "Amiga.Lib," which couldcause your program to crash, or otherwise act incorrectly.

Choosing a program nameThe last item of the group is for selection of the programname. If you didn’t choose a name for your program thelinker will automatically create a file called "a.out" in theproject path when you link your code.

After selecting the menu item "Project/SelectExecutable…" the ASL filerequester will show up. Now youcan choose a drawer and a name for your program.

Please note that there will be a file with the extension".link" in this drawer when you are using the debugger.This file contains data about the modules of the program andtheir paths.

Drag&DropOf course you may drag files from the Workbench to theproject window. If you drop an icon into the project windowit will be added to an existing section or a new one will becreated.

Controls of the Project WindowYou certainly have recognised the folding of the projectsection. The small triangle indicates if the following sectionis folded or unfolded (so you can see all its entries).

StormC User Manual 59

Page 60: StormC V3 Users Manual

4 PROJECT MANAGER◆

Folding of SectionsIf a section is not folded the triangle shows to the bottomand all entries are visible. The following pictures will showthe unfolded and the folded libraries section.

To fold/unfold a section you must click on the triangle nextto the section name. The same actions will take effect if youdouble-click the section title.

But there is more functionality in the project manager thanto fold/unfold sections.

Showing SourcesIf you double-click a source in the source section it will beopened in the editor. During loading there will be a fuelgauge that shows you the progress.

But not only sources in the Source section can be loaded thatway. You can load every entry in the following sections intothe editor by a simple double-click:

Header files ASM sourcesASM header filesDocumentationARexx scriptsAmigaGuide filesFD filesLocale catalogues

Starting a ProgramBy double-clicking an item in the section "Program," youwill start that program.

60 StormC - the professional choice

Page 61: StormC V3 Users Manual

Keyboard control◆

If you hold the <ALT> key while double-clicking such anentry, you will start the program in debug mode.

Open a Child ProjectOf course there can be projects within projects, so it is easyto administrate the source for shared library development, ormultiple program projects, as well. With a simple double-click on such an item in the project manager you can openthe project.

Keyboard controlYou have certainly recognised that the section title and theitems will stay selected (inverted) after selection. This is anindicator for keyboard control.

Cursor keysWith the keys <UP> and <DOWN> you can move theinverted beam up or down. If there is a horizontal slider atthe bottom of the project manager window you can move itwith the keys <LEFT> and <RIGHT>.

ReturnThe <Return> key has the same action as a double-click withyour mouse. If the inverted beam is at a section title and youhit <Return>, the section will be folded/unfolded. When theinverted beam is over a document, a source file, or anythingthat could be edited in an editor, it will be opened there ifyou hit <Return>.

If you are deleting a file the way described

here this will not really delete the file. It will only delete its appearance in the project manager. The file will still be available on your hard drive. Of course you can delete files or complete sections in the project manager. You might select the menu item "Edit/Delete" or you can press <DEL> or <Backspace>.

Deleting Items of a Project

If you want to delete a whole section of your project youmust select the title of it. A requester will appear, to verifywhether you really want to delete this section or not.

Organising files of a projectThe biggest advantage working with a project manager is theorder of all the parts of your project. This will normally be

StormC User Manual 61

Page 62: StormC V3 Users Manual

4 PROJECT MANAGER◆

done automatically, but I will show you some methods to doit even better.

As you know it is very easy to create a new project. You onlyhave to click on the icon "New Project" on the toolbar anda standard project template will be opened. This project hasall settings that are needed to start, but one thing is missing:there is no file name and you have not defined the place tosave it.

Every project should have its own drawer. Naturally you canstore more than one project in a drawer, but you shouldn’tdo this, as then you will not know which header files anddocuments belong to each specific project.

A simple click on the "Save Project" icon on the

toolbar is enough to save your project. As an alternative you can select "Save" or "Save As..." from "Project" as well.

The first step after creating a new project is to save it. Evenif you did not add anything to it this is the best way to giveyour project a name and its own drawer. You can do it withone step. Hit the "Save Project" icon on the toolbar. AnASL filerequester will appear. Now type in the name of thenew drawer and the name of the project e.g. "New Drawer/My Project". Now you have created a drawer called "NewDrawer" and a project called "New Project. ¶". Theextension ".¶" will be added automatically.

Please note that you have to enter <Return> first.

Unfortunately a click on the "Save" icon will not test whether you want to create a new drawer.

As soon as you hit <Return> you will be asked if you want tocreate a drawer named "New Drawer". Confirm it with "OK"and press <Return> or click "Save".

Project specific headersClass and structure definitions that are used in severalmodules should be collected into a common header file. Inour example debugger tutorial, there is a project specificheader file called "address.h". When you look at the sourceto "main.c" and "address.c," you will see that theseheader files are called with quotation marks and thestandard headers with angle brackets "<>".

The options of the standard include drawer

will be described in the following sections.

Looking at the quotation marks on "#include," thecompiler decides whether to load the file out of the standardinclude drawer or from the same drawer as the source.

The following line will cause "stdio.h" to be loaded from"StormC:Include" by the compiler. If it does not find it atthis location, all alternatives will be tested before an errorreport appears.

62 StormC - the professional choice

Page 63: StormC V3 Users Manual

Makescripts◆

#include <stdio.h>

This line

#include "address.h"

causes the compiler to look in the same drawer as the sourcefor "address.h."

As a result, you should not use a special drawer for projectspecific header files. It is better to store them in the samedrawer as the source. You should not store them in thestandard include drawer, either. First of all, this does nothelp you keep your files in good order, and it also preventsthe project manager from knowing about the dependencebetween source and header files.

Header files which are in angle brackets "< >" will cause noautomatic re-compilation if they are changed in the editor.However, the dependency of header files which are stored inthe source directory, and which are enclosed with quotationmarks, will be regarded. That means that after a change ofthese header files, the sources in which the headers areincluded will be recompiled automatically.

Documentation, scripts ...You should use separate drawers for documentation,AmigaGuide files, Installer and ARexx scripts if there aremore then two files per section.

You don’t have to keep this order, because the projectmanager will show everything very clearly (divided insections). But from time to time you will look at your oldprojects, and then you will see the advantage of goodstructure. The more you work on the structure of yourproject the easier it will be to find the files in old projects.

MakescriptsThe rules behind a "Make" are essentially very simple. Firstof all, all files in the project are checked to see if they needto be recompiled.

In the case of a C source file this means that the file dates ofits object and debug files are compared to that of the sourcetext and of any header files that it may #include. If any of

StormC User Manual 63

Page 64: StormC V3 Users Manual

4 PROJECT MANAGER◆

these is newer than either the object or debug file, the sourcefile needs to be recompiled.

The source file also needs to recompiled if one of the headerfiles has been changed by some other action by the compiler.This may be the case for instance when the "catcomp"program is used to generate a header file from a Locale file.

Once it has been determined which files are to be recompiledor re-linked, each of them is handled by sending thecorresponding ARexx commands to the StormC compilerand the StormLink linker. These commands are thenexecuted in turn.

Makescripts are used when other files than just C andassembler sources need to be translated:

The "Select translation script..." menu option lets youenter an ARexx script for the active project or - if a sectiontitle has been selected - for all files in a section. These scriptsmake it possible to invoke external compilers such as eg."catcomp" to compile Locale files automatically.

They are called by the project manager whenever the projectis to be recompiled. Makescripts should have filenamesending in ".srx". Files with this extension to their namesare also included in the ARexx section.

Selecting the "Remove translation script" menu optionwill remove the makescript from a project entry or from allentries in a project section.

The rules for determining whether a project file that has amakescript attached should be recompiled, are essentiallythe same as they are for C source files.

A file is always recompiled during the first "Make" after amakescript has been added to it.

As an example of what a makescript looks like, the"catcomp.srx" script is explained below:

The script’s arguments are the file name (ie. the path to theproject entry) and the base project path. Both are enclosedin quotes to allow the use of spaces.

64 StormC - the professional choice

Page 65: StormC V3 Users Manual

Makescripts◆

The argument list must be terminated by a full stop, so thatany additional arguments that may be passed by futureversions of the compiler will be skipped.

PARSE ARG '"' filename '"' '"' projectname '"' .

The object filename is constructed from the filenameargument. This isn’t necessarily a file that is going to belinked and whose filename ends in ".o", but simply the filethat is to be created. Catcomp happens to create a headerfile.

objectname = LEFT(filename,LASTPOS('.cd’,filename)-1)||".h"All output is sent to a console window.

SAY ""SAY "Catcomp Script c1996 HAAGE & PARTNER GmbH"SAY "Compile "||filename||" to header "||objectname||"."

In order to allow the Project Manager to determine when thefile should be recompiled, the object filename must becoupled to the project entry. If this statement were to beomitted, the makescript would be called for every "Make".

A maximum of two object filenames may be given as follows:

OBJECTS filename objectname1 objectname2

These names are then attached to the entry and the files arechecked when recompiling.

See also the script "StormC:rexx/phxass.srx".

The OBJECTS statement should not be used if the makescriptis used for calling an assembler in the section "AsmSources". For this section the object names are derivedautomatically.

OBJECTS filename objectname

This is where the translating program is called. Errormessages are printed in the console window.

ADDRESS COMMAND "catcomp "||filename||" CFILE "||objectname

As "catcomp" creates a header file, it is advisable to enterthis header file into the project. The QUIET parameter

StormC User Manual 65

Page 66: StormC V3 Users Manual

4 PROJECT MANAGER◆

represses any error messages in case the header file shouldalready be included in the project.

ADDFILE objectname QUIET

/* End of makescript */

Almost any makescript can be built along these lines.Another statement may be useful in some cases:

DEPENDENCIES filename file1 file2 file3 ...

This statement connects the project entry to further fileswhose dates will be checked to see whether or not themakescript should be called. The file named in the projectentry itself will always be checked and need not be specifiedusing this statement. Using this statement makes sense incases where the script involves any extraneous files (theStormC compiler for instance uses it to declare any headerfiles that a source file includes with #include "abc.h"; notethat this is not done for headers included with #include<abc.h>).

Makescript settings are ignored for the project section thatcontains C sources; these files are always run through theStormC compiler. The section containing assembler sourcefiles on the other hand allows the use of makescripts -although it will use the built-in default rule for StormASM(which in turn invokes the PhxAss assembler) if nomakescript is set.

Passing arguments to makescriptsThe script receives the filename (that is, the path to theproject entry) and the project path as arguments. Both pathsare enclosed in quotes to allow the use of whitespace in fileor directory names.

Next comes a numeric argument whose value indicateswhether the object files should all be written into a singledirectory.

0 means that the object file should be stored in the samedirectory as the source file;

1 means that the object file is to be stored in the object-filedirectory.

66 StormC - the professional choice

Page 67: StormC V3 Users Manual

Passing arguments to makescripts◆

The name of the object-file directory - quoted like the otherpaths - is passed as the next argument (regardless of the valueof the previous argument, ie. even when the precedingnumeric argument is 0).

The object-file directory is only interesting to programs thatgenerate code. Source-generating makescripts (eg."catcomp.srx") will always write their object files to thesame directory that the file in the project entry resides in.Thus only assemblers and other compilers really need to careabout the object-file directory.

Makescripts for assembly source files are an exception in thatthey take an additional third argument: The name of theobject file. This name must be used when creating theassembler object file. The path to the object-file directory isalready included in this name, if necessary.

The argument list must be terminated by a full stop so thatany additional arguments that may be passed by futureversions of the compiler will be skipped.

A complete PARSE statement for makescripts (other than onefor assembler sources, as explained above) is composed asfollows:

PARSE ARG '"' filename '"' '"' projectname '"' useobjectdir '"' objectdir '"' .

For an assembler makescript this would be:

PARSE ARG '"' filename '"' '"' projectname '"' '"' objectname '"' useobjectdir '"' objectdir '"' . Ready-made makescripts

The directory "StormC:Rexx" contains several ready-to-usemakescripts. You may want to adapt them to different usesand situations:

Assembler scriptsMakescripts for assemblers differ from other makescripts inthat they may not contain the OBJECTS statement.

"phxass.srx"

StormC User Manual 67

Page 68: StormC V3 Users Manual

4 PROJECT MANAGER◆

This script translates an assembler file using the PhxAssassembler. This script is really superfluous because theassembler is supported by the StormShell directly, but maybe useful if you want to use different assembler options.

"oma.srx"

This script translates an assembler source file using the OMAassembler.

"masm.srx"

This script translates an assembler source file using theMASM assembler.

Other scripts:

"catcomp.srx"

This script translates a Locale catalogue file by invoking theprogram catcomp.

"librarian.srx"

The StormLibrarian can also be controlled throughmakescripts. A project entry in the "Librarian" section canbe loaded directly into StormLibrarian by double-clicking itwith the mouse, or the linker library can be created simplyby double-clicking it while keeping the Alt key pressed. Butif a project should always create a link library, the use ofmakescripts is recommended. The list of object files iscreated in StormLibrarian as usual. The makescript theninvokes the StormLibrarian, which not only automaticallygenerates the library, but also declares the linker library as anobject (using OBJECTS) and all object files in the list asdependant files (using DEPENDENCIES). After the first Makethis will cause the linker library to be created anew wheneverany of its C or assembler source files has been recompiled.

The library will also be recreated if its list of object files hasbeen modified using the StormLibrarian.

"fd2pragma.srx"

This makescript translates an FD file into a header filecontaining the necessary "#pragma amicall" directives fora shared library. This script shouldn’t normally be necessary

68 StormC - the professional choice

Page 69: StormC V3 Users Manual

Saving of the paths◆

as the linker writes this header file automatically whenevera shared library is linked.

Saving of the pathsWhen saving a project you will give a filename and a pathfor storage. Before you save a project all files are stored withtheir full path which is sometimes very long. After the save,all these paths are shortened to relative paths. This meansthat all files that are stored in the same drawer will be storedwith their name only. The path is no longer relevant.

StormC User Manual 69

Page 70: StormC V3 Users Manual

4 PROJECT MANAGER◆

PROJECT SETTINGS

Every project has its own settings for the compiler, linkerand RunShell. Maybe that doesn’t sound difficult, but thereare many settings and connections that should be thoughtabout before compiling a new project.

First there are some principle settings, e.g. default paths forIncludes and linker libraries, standard definitions and thesettings for the program start.

Next, the more complicated settings for code generation.The global settings for a project, whether the compiler willrun in C++ or ANSI-C mode, can be changed for every sourcefile.

Many of these settings will be set to a default if you create anew project. Some of the settings are project specific andmust be set according to the needs of the project. As anexample: before starting the linker you must decide whetherto build a driver or a shared-library. If you want to create ashared-library, but the settings are for a normal program, theresult will not be satisfying, but you can correct this veryeasily by changing the settings and starting the compileragain.

The following sections will explain the individual controls ofa project. You should open a new project and choose themenu item "Settings/Project Environment...". Thefollowing requester has a cycle gadget to change betweeneight different pages. The gadgets "OK" and "Cancel" willaccept or cancel all these settings. You should use "OK" toaccept all these settings or click "Cancel" if you don’t wantthem to be accepted or if you just wanted to have a look atthem.

Paths and global settingsThe first control is the settings for the includes.

70 StormC - the professional choice

Page 71: StormC V3 Users Manual

Paths and global settings◆

Include pathThe pre-processor reads the definitions for the standardfunctions out of the include files. You use the pre-processordirective "#include" to include these files into your source.As you may know, there are two possibilities for this: You canput the include file name in quotation marks like #include"this_one" and the pre-processor will look for it in the samedrawer as the source, or you can use the angle brackets like#include <this_one> and the pre-processor will recognisethem as standard include files, and look for them in thepredefined directory. The predefined directories are listed inthe listview you will see at the left side of the requester. Youcan define more than one directory for searching standardinclude files.

NewWith a simple click on "New" you can create a new entry inthe listview. You can type the complete path into the stringgadget under the "New" button. If you do not know theexact path, or simply don’t wish to type it, you can use theASL filerequester to look for it by clicking the icon next tothe string gadget.

RemoveClick on "Remove" to delete the selected entry from the list.

Header FilesOne way to increase the speed of the compiler is to createand use pre-compiled header files. The pre-compiled headerfiles are always present after you create them once. Anotheradvantage of the pre-compiled header files is that all files areassembled to one big file which can be loaded faster.

To tell the compiler where the header files are end and yourprogram starts, you must mark it with a "#pragma header"statement. One simple way is to put the "#includes" of allheaders you didn’t write yourself (e.g. OS includes), or whichwill not be changed, at the beginning of your source. The"#pragma header" statement should follow. After that, listyour own header files and the rest of your program.

The pragma statement has no effect until you activate"Write Header File" in the cycle gadget "Header Files"and start the compilation of any changed modules. As soonas the compiler reaches the pragma statements it will stopcompiling your source, and the pre-compiled header file willbe written with the given name to the predefined drawer.

StormC User Manual 71

Page 72: StormC V3 Users Manual

4 PROJECT MANAGER◆

Before you start the compiler again you should switch thecycle gadget "Header Files" to "Read Header File". Nextyou should enter the path to the pre-defined headers intothe string gadget below. You can use the ASL filerequester forthat by clicking on the icon next to the string gadget. Thecompiler now uses the pre-compiled header file and looks forthe statement "#pragma header" to start furthertranslation.

Working memory - WorkspaceThe compiler will need some free RAM for code generationand assembling, but StormC does not know how much inadvance, so you must choose a value for workspace. If theworkspace is not large enough, the compiler will stop andgive you the error message "Workspace Overflow".

A value of 100 KB will be enough for most of your programs.But if the compiler gives you an error message you shouldraise this value and start compilation again.

Definitions and WarningsWith these controls you can choose pre-processor warnings,and you can select the predefined pre-processor symbols.

#define

In this list you can predefine pre-processor symbols. Everyitem in this list will be treated the same as if you had entereda "#define" line at the beginning of your source.

An example: You have inserted several assert() calls in yourprogram and you included the file "<assert.h>". To disablethese calls, you must add "#define NDEBUG" somewhere atthe beginning of your source, before the "#include

72 StormC - the professional choice

Page 73: StormC V3 Users Manual

Definitions and Warnings◆

<assert.h>" line. Or, you may simply insert "NDEBUG" intothe list of predefined pre-processor symbols and mark thegadget in front of the string gadget.

Enable/DisableTo disable a special pre-processor symbol for the nextcompiler run you can simply mark it with the mouse. Itappears in the string gadget below the listview and you canenable/disable it by clicking the gadget on the left side.

The controls for "#define" are nearly the same as those forthe "#include" controls in the previous section.

NewThis will create a new entry in the list and the string gadgetwill be activated. Type in the name of the new definition e.g."STORMPRAGMAS" and press <Return>. The new pre-processorsymbol will be inserted in the list now and it is activated. Ifyou interrogate "#ifdef STORMPRAGMAS" you will get thevalue TRUE.

RemoveWith "Remove" you can delete the marked item from thelist.

CharacterYou can not only define a symbol; you can also assign a valueto it. You can enter any alphanumeric character into thestring gadget. Unfortunately, the compiler only accepts onecharacter per symbol, so the entry "(11-5)" will only takethe "(" and ignore the rest. More complex definitions willneed to be done directly in the source, but you can use it forsymbol definitions for flags like "NDEBUG".

WarningsEven at runtime of the pre-processor, there can be languageconstructs that are syntactically and semantically correct,but that might be programming errors.

Nested CommentsThis warning appears when embedded comments, e.g. "/*This is a /* comment */", are found, since there mightbe a missing "*/" at the end of the comment.

Unknown #pragmaPragma statements are independent of the compiler. But ifyour sources were made for other compilers they mightcreate confusion. Normally the compiler ignores everypragma it does not know, but a warning will give you thechance to see whether you made a typing mistake.

Suspicious Macro Parameter

If a macro argument extends over 8 lines or 200 expressions,the compiler assumes that you have forgotten a closing

StormC User Manual 73

Page 74: StormC V3 Users Manual

4 PROJECT MANAGER◆

bracket. So, there will be a warning, and you will not have tolook for this error endlessly.

ANSI-C/C++ SettingsWith these settings you can control code generation anddebug output.

SourceYou can choose between "ANSI-C" and "C++" mode. If youare in C++ mode you can make some additional C++ settings.

Template FunctionsCreate All Templates Templates are a very useful and easily understandable

construct of the C++ language, but they are not easy to use.Essentially function templates have some surprisingproperties. Normally you can not say if the definition of atemplate is correct or not. Maybe you can think of adiscretionary function template for a sorting algorithm (e.g.quicksort). The type of the element of the vector that has tobe sorted is normally a template argument.

The programmer can solve the problem by implementingthe needed function for the datatypes by himself. Since youare working with more than one module on a bigger projectthe compiler can not know which of the not-created, butneeded functions exist as finished ones anywhere within theproject. The compiler has two different strategies to solvethis problem. The first one will be activated by choosing theentry "Create All Templates". The compiler assumes thatyou didn’t write your own templates, so it generates alltemplates which are needed, but are not already defined. Ifan error occurs during this process it will be reported.Functions that are created but that are not needed will bedeleted by the linker, later.

74 StormC - the professional choice

Page 75: StormC V3 Users Manual

ANSI-C/C++ Settings◆

Another strategy will be selected if you do not mark "CreateAll Templates". In this case all templates will be createdtoo. If there an error is found in one of the functions theprocess will be halted. There will be no code generation forthe faulty function, and the programmer will not bebothered with the error message. The compiler assumes thatall templates that can not be created without an error aredefined elsewhere in the project.

I advise you to switch on this option during programdevelopment, because only in this case will you will get adetailed error message about errors in the template. But ifyou are working with finished template libraries or if you areporting an existing program, there might be a need to switchoff the generation of templates.

If you ask asking yourself why you have to care about theright strategy, I will tell you how to implement a functiontemplate correctly:

• Do not create templates the first time you compile yourcode.

• The linker tries to link the project and generates a list ofall undefined functions.

• In the final compiler run, all modules that might containa helpful template definition will be compiled anew.With the help of the list, generated by the linker, it isclear which functions must be generated.

Such an implementation would not only be very large-scale,but also very slow because some modules must be compiledtwice every time.

ExceptionsUsing ExceptionsSometimes it is an advantage if you compile a "classic" C++

program that does not use exception handling in a specialcompiler mode. The related keywords ("catch", "throw","try") will not be recognised, and in the created code thereis no book keeping of the needed destructor calls. If "UseExceptions" is switched off, exception handling is notpossible any more.

StormC User Manual 75

Page 76: StormC V3 Users Manual

4 PROJECT MANAGER◆

DebuggerIf you choose to create a debug file the compiler will generatea file for each translation unit from which the debuggercould take the needed information. There are twopossibilities: "Small Debug Files" and "Fat Debug Files".

Small Debug Files Small debug files contains only a few pieces of data aboutvariables. They are stored in the debug files of every module.There is no information about "#include" files which are inangle brackets within a debug file.

Fat Debug Files These files contain all data types, structs, and class members.The debug files of every module are accordingly big.

Create Symbol Hunks Instead of the StormC source-level debugger you can use asymbolic debugger like "MetaScope" as well. To get someimportant information you should create the so-called"symbol hunks".

ASM source without C source

If you selected this option the compiler will generate anassembler listing for every file it has compiled successfully.The assembler source will be stored in a file with the samename as the C source but the ending ".s".

If you are familiar with other compilers you might wonderabout the "obviously" well optimised assembler code. Toclarify this: The compiler generates intermediate code in aninternal binary format that looks like assembler source insome way, but that has nothing to do with an ASCII file. The"assembler" will translate this intermediate code to realmachine code while doing some optimisations.

The assembler source generated by StormC correspondexactly to the code which is translated to machine codedirectly. So you do not need the help of a re-assembler tolook at the quality of the generated code.

ASM Source With C Source

If you want to have the corresponding C source (as acomment) within the assembler source you should selectthis option.

Code GenerationExtra Hunk For Every Function

A hunk will be generated for every global variable and everyfunction during code generation. As a result the linker caneliminate every unused function and the code size will

76 StormC - the professional choice

Page 77: StormC V3 Users Manual

ANSI-C/C++ Settings◆

decrease. This is very practical if you want to program alibrary, but it has a price: functions of a translation unit cannot use identical strings collectively and they cannot calleach other via PC relative addressing. This can result in alarger, slower program.

Processor Specific Code GenerationThe proven MC68000 processors are a dying species in theAmiga world. 32-bit processors (68020 to 68060) andFloating Point Units (68881 and 68882) have prevailed. Soprogrammers have new and powerful machine commandswhich give them a sometimes astounding increase in speed.The 32-bit processors have some important features like theoperators for longword multiplication and division and forthe handling of arrays and bit fields.

If you generate code for 68020 and above or for

an FPU these programs might not run on your old Amiga any more. They will certainly crash suddenly.

By using the cycle gadget you can tell the compiler whichcode it should generate (68020/30/40/60).

Programs which do many floating point operations will besped up by using an FPU (Fast Floating Point Unit). Theoption "Use FPU" will generate special code for the FPU.

If you switch to "68040/60" optimisation the use of the FPUwill be activated automatically. This is because bothprocessors have a built-in FPU.

Small and huge code model

StormLink supports "near code". In this model, pc-relativeaddressing of functions is used to get faster code and smallerprograms. If the NearCode hunk gets bigger than 32 Kbytes,StormLink inserts a "jump chain" between the single hunksto make a call with more than 32 Kbyte address rangepossible.

Small and huge data model

A program which is created in the small data model has asingle hunk which contains the pre-initialised data of theprogram and the uninitialised data (BSS). Access to this hunkis handled by address register relative addressing. Theseaccesses have the advantage of being faster and shorter than32-bit absolute accesses.

In the small data or code model, only SHORT will be used foran address. These are 16 bit or 2 bytes. This makes theProgram shorter and faster but the program can only be 64Kbytes in size. The short addressing is possible though atrick. One register of the CPU, normally A4, points at a place

StormC User Manual 77

Page 78: StormC V3 Users Manual

4 PROJECT MANAGER◆

in the data area of the program and all addresses can becalled by an offset to this register.

Small data model (a6)

"Small Data Model (a6)" is a format that is available inStormC only. It is mainly the same as the NEAR format, butthe base register is A6 instead of A4.

In a shared library the program has no elegant method to getthe value of the base register, but it does get the library basein register A6.

Quality of the OptimisationTo improve the quality of the code requires a lot of RAM andan increase in the translation time.

OptimisingAt this time the compiler knows 6 levels of optimisation. Youmay select the level with the slider or by entering thenumber directly.

The following optimisations will be done by the respectivelevels:

Level 1 The first level optimises basic blocks. A basic block is asequence of code statements which do not contain anyjumps. Successive blocks will be joined to make lateroptimisation easier. Unused blocks (which are not jumpedto) will be deleted. This step will be repeated until the codecan no longer be improved. The joining of successive blocksand the deletion of blocks never used will also occur inhigher levels.

Level 2 Useless statements, such as assigned variables that are neverused, will be detected and deleted.

78 StormC - the professional choice

Page 79: StormC V3 Users Manual

Quality of the Optimisation◆

Level 3Automatic registerisation of temporaries and variables willbe used if possible.

Level 4Assignments to variables that are never used will be deleted,and the whole program will be checked again until noredundant assignments can be found.

An example:

At this useless function

void f( int i){int j = i+1;int k = 2*j;}

the second assignment will be recognised as useless. Fromlevel 4 on the code will be checked again so the first one willbe deleted too.

Level 5During M680x0 code generation, redundant MOVEcommands will be elimated.

So

move.l 8(a0),d2 add.l d2,_xyz

will become

add.l 8(a0),_xyz

Level 6During expression evaluation, temporary variables will becreated at code generation for provisional results of anykind. They may be put into processor registers later.Temporary variables from lower levels will be recycled ifpossible, to keep the number under a certain boundary.

The expression "a*b+c" will become intermediatestatements like:

h1 = a*bh1 = h1+c

From level 6 on these temporary variables will not be re-usedprincipally. So there will be code like

StormC User Manual 79

Page 80: StormC V3 Users Manual

4 PROJECT MANAGER◆

h1 = a*bh2 = h1+c

In a later optimisation step, a test is made to see if it makessense to put "h1" and "h2" into the same register. Becausean increasing number of temporary variables can cost a lotof time and RAM, this can be an expensive optimisation, butit helps make the best use of the CPU registers.

Compiler Warnings

Some constructs and expressions are syntactically andsemantically correct, but they are a little strange and mightbe the consequence of a programming mistake, so there areeight warnings which can be switched on and off as personalpreference.

These are the warnings:

Standard of the languageMissing Prototypes If a prototype is not declared for a function, there will be a

warning in C mode. In C++, this is an error.

Old K&R Parameter "K&R" means "Kernighan & Ritchie" the Pre-ANSI pseudo-Standard. With this option you will get a warning if afunction is declared in this old style.

Reference to temporary Variables

According to the C++-2.0-Standard, it is an error if aReference will be initialised to a non-constant type with anon-L-value and a temporary object must be inserted. As thisrule did not exist in the first standard there is no real errormessage but a switchable warning.

80 StormC - the professional choice

Page 81: StormC V3 Users Manual

Compiler Warnings◆

An example:

void dup(int &ir) { ir *= 2; }

void main() { int i; dup(i); // OK long l; dup(l); // ATTENTION! }

As "I" must be converted from "int" to "long" a temporaryobject must be inserted. The programmer will be surprisedbecause at the second "dup" call there is a side effect on theargument. So the new C++ rule is very sensible.

SecurityMissing "Return"If there is no "return" statement in a function which has

non-"void" return type, then there is certainly somethingwrong. You should always switch this warning on.

Empty StatementA statement like "69;" makes no sense, so there is probablysomething wrong with it. A well-known error is the call to aparameter-less function without an argument list, e.g."test" instead of "test();".

Unsure StatementThis option is warning if there is an implicit type change(without CAST) from integer to floating point types.

Suspicious "="This is a popular construct "if (a=b)...". It is correct andmany programmers like it very much, but it is a beginnererror as well if it is used instead of "if (a==b)". If thisoption is active there will be a warning if an "=" follows alogical expression e.g. "if", "while" or "do" and operandslike "||", "&&" or "!".

OptimisationUnused VariablesThere will be a warning if there is a declared variable that is

never used, or if a variable is used but not initialised.

StormC User Manual 81

Page 82: StormC V3 Users Manual

4 PROJECT MANAGER◆

Path Settings and Linker ModesThe Settings of "Linker Options 1" set the defaults of howa program has to be linked.

Generation of ProgramsLinking Programs With the first cycle gadget you will choose the manner of

program of the project. "Link Program" will use thestandard library. If the next cycle gadget says "StormCStartup-Code" the file "PROGDIR:startup.o" will belinked to the program.

No Linking The Linker will not do anything. After the compiler run, theproject will be "ready compiled". The object and debug fileswill be stored, but no executable will be created.

Link as Shared Library

The linker creates a function table out of the indicated FDfiles and imports the standard shared library functions"LibOpen()", "LibClose()", "LibExpunge()" and"LibNull()". If "StormC Startup-Code" is selected the file"PROGDIR:library_startup.o" will be linked to theprogram.

StormC Startup-Code As said before, the standard Startup code will be linked to theprogram when this option is selected. The Startup-code canbe found in the directory "PROGDIR:". Shared libraries willuse the startup code "library_startup.o," the others"startup.o".

Without Startup-Code

Normally only "drivers" and "handlers" are linked withoutStartup-Code. Here the libraries mentioned in the projectwill be linked, but the Startup-Code will not be used.

82 StormC - the professional choice

Page 83: StormC V3 Users Manual

Path Settings and Linker Modes◆

Own Startup-CodeIf this option is selected the string gadget is activated andyou can enter your own object file that should be used as theStartup-Code for linking.

Link All ObjectsNow all functions and global variables from the object filesof the project modules will be linked to the program, even ifthey are not used. Of course this does not count for functionsin libraries.

Write Map FileStormLink creates a file which contains all symbols from thegenerated programs with their assigns in the finishedprogram. Here you see part of a linker map:

_cout = $ 24 in hunk 1 <stormc:lib/storm.lib> ( Far Public )_std__out = $ 32 in hunk 1 <stormc:lib/storm.lib> ( Far Public )_std__in = $ 16 in hunk 1 <stormc:lib/storm.lib> ( Far Public )_cin = $ 8 in hunk 1 <stormc:lib/storm.lib> ( Far Public )_clog = $ 40 in hunk 1 <stormc:lib/storm.lib> ( Far Public )_std__err = $ 4E in hunk 1 <stormc:lib/storm.lib> ( Far Public )_cerr = $ 40 in hunk 1 <stormc:lib/storm.lib> ( Far Public )

The first entry of a link is the name of the symbol. Then thehexadecimal value follows, then the hunk in the programwhere this symbol can be found, the object file it came from,and the memory class of the hunk. The map file has the samename as the generated program with the ending ".MAP".

Protocol Name Conflicts

StormLink looks for multiple occurrances of symbols. Ifsomething is found, the name of the file in which thesymbol was defined will be shown. The test will be made onlibraries as well, because names could be multiply used, butwith different meanings.

A good example is the C function "printf". It is in"MATH.LIB" as well as "Storm.Lib", but the one in"Math.Lib" can print floating point values.

Offset Of Linker Data base

Sets the offset of the data section for the created program tothe value: first data object + number. If your programcontains a lot of data and StormLink gives you the errormessage "16 bit Reference/Reloc Overflow," a basenumber of 0x8000 could fix the problem. If this does nothelp, you must use 32 bit addresses (HUGE data model).

StormC User Manual 83

Page 84: StormC V3 Users Manual

4 PROJECT MANAGER◆

Version This sets the global constant "__VERSION" to the value of the

string gadget.

Revision This sets the global constant "__REVISION" to the value ofthe string gadget.

Library PathLoad Logfile If StormLink can not find a symbol, it prints the message

"ERROR 25 ..." Before that is a text which shows which fileit has to load to find the symbol. The logfile which is loadedwith this option contains information about object files andthe there defined symbols. It has the following setup:

<filename> <= This is an object file <symbol>

<symbol>

If "Load Logfile" is active the name of the logfile can beentered into the string gadget.

Warnings32 Bit Reloc When the program contains "32 Bit Reloc" StormLink

outputs a warning. This option is good for writing positionindependent programs.

OptimiserOptimise NearCode Model

When this option is set StormLink runs an optimisationpass. If it detects a 32 Bit Reference which points to the samehunk, StormLink tries to change it into a PC relative, so thereloc entry will be freed, which saves 4 Bytes.

This method may lead to incorrect programs. The optimiseronly has a small disassembler, which only knows thecommands JSR, PEA and LEA. It has no idea of how todistinguish between code and data in code hunks. Theoptimiser will be called for global references only, whenbuilding references between object modules. For relocentries an assembler or a compiler should do theseoptimisations.

84 StormC - the professional choice

Page 85: StormC V3 Users Manual

Hunk Optimisations and Memory Settings◆

Hunk Optimisations and Memory Settings

Summarise HunkCreate Single HunkStormLink will only create one CODE hunk which contains

all code, data and BSS sections. This is an interesting thingfor game programers.

A reloc routine has to work on one hunk only. When theprogram is in SmallData model you can write completely PCrelatve programs in a high-level language. The base registerfor data access (normally A4) will be initilised with:

lea _LinkerDB(PC),a4

All other accesses are made with d16(pc) or d16(a4), andthe program will not contain any absolute addresses. Suchprograms can be loaded very fast and are re-entrant in mostcases. In conjunction with "Create ROM Code" you will geta program that can be loaded to any even address byRead(file, buffer, len) and is immediately usable there. Onecondition is that the program does not use absoluteaddresses. So you should use "32 Bit Reloc" in any case.

Resident ProgramsA program which should be resident in memory has highrequirements in the runtime system. A global variable mustnot be declared the way another instance of the programcould use it.

Principally a resident program has a small data model and itcopies all data at every invocation, and works with the copy.It is important that the program does not contain anyabsolute addresses, because they always point to the original

StormC User Manual 85

Page 86: StormC V3 Users Manual

4 PROJECT MANAGER◆

data segment. These accesses can not be redirected to thecopy. The option "RESIDENT" will switch these warnings on.

Write Data-Data-Relocation

If there are fixed 32 Bit Relocations of data to Data/BSS youcan tell StormLink to create an internal relocation table forthe program, so that the Startup-Code can compute therelocation for the copy of the Data/BSS hunk on its own.

Manner of MemoryYou can select "Standard", "Chip RAM", "Fast RAM" and"configurable". You should use "Standard" so theprogram can choose the best settings according to theavailable hardware. With these settings you can force theentire program or single hunks to be loaded into Chip or FastRAM.

ROM CodeCreating ROM Code

When the program uses the data relative to

an address register, the BSS hunk will be assumed to be after the data hunk. The address for BSS is the address of the data + length of data. The options for SmallCode, SmallData and SmallBSS will be set automatically, so there will be no fragmentation. With the additional option "32 Bit Relocation" and corresponding Startup-Code, you can write totally PC relative programs.

When you want to burn an EPROM, you must use thesesettings. The output file contains pure binaries of the codeand data hunks. The BSS hunk should be located at a certainaddress with "AllocAbs()". Code and data hunks arerelocated to the pretended address. The AmigaDOS overheadof reloc hunks, etc. are not added. After the code there is onlydata in the target file.

86 StormC - the professional choice

Page 87: StormC V3 Users Manual

Call of the executable program◆

Call of the executable program

Execute EnvironmentStacksizeThe string gadget or the slider can be used to adjust the

stacksize for the program, which will be reserved by theRunShell.

TasknameYou can enter the name of the Exec task here.

Current DirectoryYou can enter the name of the directory that will be thecurrent one for the program.

PROGDIR:You can enter the name of the home directory of theprogram.

Start From CLIWhen started from a Shell you can supply arguments whichwill be evaluated by C by the parameters "argc" and "argv".At program startup from within the developmentenvironment, you can simulate this manner of parameterhandling.

Command NameThe CLI command name is the name that is handled by"argv[0]".

StormC User Manual 87

Page 88: StormC V3 Users Manual

4 PROJECT MANAGER◆

Arguments Here you enter the arguments that will be given to the

running program by the development system.

I/O SettingsYou can choose between "Console" and "Files" for Input/Output. "Console" will use "stdout" and "stdin".Normally a console is opened with "CON:". When you wanta window to be opened with special attributes you mustprovide further data. You can enter the starting size, theposition and title of the window. The syntax is as follows:

CON:x/y/width/height/title/options

X Number of pixels from the left border of the screen to the leftborder of the Shell window. When you do not enter a value(//), the lowest number of pixels will be used.

Y Number of pixels from the upper border of the screen to theupper border of the Shell window. When you do not enter avalue (//), the lowest number of pixels will be used.

Width Width of the Shell window. When you do not enter a value(//), the lowest number of pixels will be used.

Height Height of the Shell window. When you do not enter a value(//), the lowest number of pixels will be used.

Title This defines the Shell window title.

The parameters of the options must be separated by a slash.

AUTO The window will be opened automatically if the programneeds data or wants to provide output. After the Shellwindow is open you can enter data immediately.

ALT When you click the zoom gadget the window will be resizedand repositioned according to the values given.

BACKDROP This window will be located behind all Workbenchwindows. You can not put it in the foreground, so you mustchange all other windows to have a look at this one.

CLOSE The window will get all standard symbols including the closegadget.

88 StormC - the professional choice

Page 89: StormC V3 Users Manual

Save Project◆

INACTIVEThe window will be opened, but it will not become the activeone.

NOBORDERThe window will not have a left or bottom borders. Therewill only be zoom, fore/background and close gadgets.

NOCLOSEThe window will be opened without a close gadget. Whenconsole window is opened with AUTO there will be a closegadget automatically added.

NODEPTHThe window has no fore/background gadget.

NODRAGThe window can not be moved. There is zoom and fore/background gadget, but no drag gadget.

NOSIZEThe window has a fore/background gadget only.

SCREENThe window will be opened on a public screen which mustalready exist. You must enter the name of the public screenafter the key-word SCREEN.

SIMPLEWhen you enlarge window size the new area will be filledwith text so you will have a look at parts that were out of thevisible area before.

SMARTWhen you enlarge window size the new area will NOT befilled with text. This saves memory.

WAITThe window can only be closed with the close gadget or bypressing <Ctrl>+<\>. If WAIT is the only option no closegadget will be available.

Input/OutputWhen you select "Files" on the upper cycle gadget the stringgadgets "Output" and "Input" become available. You canenter the path and the name of the file where all output datashould be stored at "Output" and the corresponding onesat "Input".

Save ProjectAfter you have made all your project settings, you can usethem for your current project by clicking "Use," or pressing<u>.

StormC User Manual 89

Page 90: StormC V3 Users Manual

4 PROJECT MANAGER◆

You can now save these settings permanently by clicking the"Save Project" icon on the toolbar or with the menu item"Project/Save"

Build your own Project Template

A project template is a default project that is used when anew project is created. It is stored as "template.¶" in thedirectory "PROGDIR:". If you want to build your own projecttemplate you should open a new project and make yourindividual settings. To save this project as your projecttemplate you must select the menu item "Project/Save AsProject Template".

90 StormC - the professional choice

Page 91: StormC V3 Users Manual

Editor5 ◆

5 StormED

tormED has some special features that makes writing source morecomfortable and easy. StormED will be used every time the source isdisplayed. This is mostly when editing your text, but if you are debugging,

your source will be shown in the editor as well. This will make it easier for you to becomefamiliar with the controls of StormC, because they are always the same. You will haveworked through "First Steps" by now, so you are more familiar with StormED. If you areworking with it often you will come to appreciate the syntax highlighting because itenable you to recognise errors very quickly. The following chapter will tell youeverything about StormED. You will see it is a wonderful tool to use.

IN GENERAL ......................................................................................................... 93

New text ............................................................................................................ 93

Controls of windows .................................................................................... 93

Open / Load Text .......................................................................................... 94Tooltypes ............................................................................................................ 94

Save Text / Save Text As ... ....................................................................... 94

Free Text ........................................................................................................... 94

Options of Text .............................................................................................. 95Tabulations and Indents .................................................................................... 95Indent ahead and behind of brackets ................................................................. 96Dictionaries and Syntax ..................................................................................... 97Dictionaries ........................................................................................................ 97Syntax ................................................................................................................ 98Colour Settings ................................................................................................... 99File Saving Settings ............................................................................................. 99Saving the Settings ........................................................................................... 100

Keyboard Navigation ................................................................................. 100Cursor-Keys ....................................................................................................... 100<Return>, <Enter>, <Tab> ............................................................................... 100

Undo / Redo .................................................................................................. 100

Block Operations ......................................................................................... 101Mark, Cut, Copy and Paste .............................................................................. 101

The Mouse ...................................................................................................... 102

S

StormC User Manual 91

Page 92: StormC V3 Users Manual

5 STORMED◆

Find and Replace ..........................................................................................102Direction ...........................................................................................................103Mode ................................................................................................................103Ignore Upper/Lower Case .................................................................................103Ignore Accent ....................................................................................................103Find ...................................................................................................................103Replace .............................................................................................................104Replace All ........................................................................................................104

92 StormC - the professional choice

Page 93: StormC V3 Users Manual

New text◆

IN GENERAL

Before you start with this section you should have learned alittle about the project manager. You will already know thatnormally you do not open a text without opening a projectfirst. Opening "pure" text is only recommended if you wantto have a quick look at it. All sources that belong to a projectshould be contained within it. Opening text will then beeasier, because you can double click on it’s entry in theproject manager.

New textClick on the icon "New Text" in the menu bar to open anew text window You can now start typing. As mentionedbefore, this is not the usual way to work. You should open anew project first and then add new text with the menu item"Project/Add File(s)…". You will find more informationon this in the chapter about "Project Manager".

Controls of windowsYou will notice that there is a row of letters at the top line ofthe editor window.

If you move the mouse pointer over the (text) icons you willget an appropriate explanation in the information line at thetop of the editor window. In the right top corner of theeditor window you will find the line and column counters.They are active for input and output. So if you want to moveto a certain line in your source simply click into the linecounter string gadget and type the line number you want to

Show end of line

Show tabsShow spaces

AutoindentOverwrite

Lock editor

Indicator for changes in text

Line-/Column counter

StormC User Manual 93

Page 94: StormC V3 Users Manual

5 STORMED◆

go to. As soon as you hit <Return> the cursor will jump tothe new position (if you have chosen an existing linenumber!).

Open / Load TextYou will probably have wondered about the differencebetween opening and loading text.

The menu item "Load" is only available when an editorwindow is active. The text will be loaded into this editorwindow.

If you "Open" text this will open a new editor window.

TooltypesAll attributes of texts (like text colour, tab size, bracketindent) and the size of windows are stored in the tool typesof the respective icon of this particular kind of text. They willbe applied when opening and loading. At loading the size ofthe window will not be recognised.

Save Text / Save Text As ...If you create new text it will be named "unnamed". Thisappears in the title bar of the editor window. If you made anyinput to this text "Save" and "Save As..." will have thesame effect. The ASL filerequester will be used for selectionof a filename. Unfortunately you cannot double-click tomake this selection because ASL does not support this. If youstored the text once it will be overwritten every time youchoose "Save". The tool type (window size, text attributes)will be adjusted as well.

Free TextTo remove the text in your active editor window you candispose of it’s contents. Choose the menu item "Project/Clear". This item is only available if there is an active editorwindow. The text will be disposed of but the window willstay open so you can load another one or start typing a newone. When text has not been saved before you will be askedto do so or to accept the disposal.

94 StormC - the professional choice

Page 95: StormC V3 Users Manual

Options of Text◆

Options of TextBefore explaining further functions of StormED you willneed to know more about the options of the editor. Thefollowing sections will always refer to these options, becausemost of the functionality of StormED depends upon it. Thechapter "Project Manager" has already explained the globaloptions of the editor so here we will only discuss the textoptions.

To get the options requester you must activate an editorwindow and choose the menu item "Settings/Text…". Arequester will appear on the screen similar to the one of theproject options.

At the top of the requester you will see paging gadgets withthe following titles:

Tabulations and Indents

TabulationYou can change the width of the tab stops with the slider oryou can type its value into the string gadget. Values between1 and 16 are allowed.

C/C++ Bracket Blocks

Most C programmers use a special structuring of their sourceto get a better overview. There is no standard instruction forthis and so there are many possibilities of how this can beachieved. We therefore leave this up to you. You canconfigure the options for some automation to makestructuring easier.

When you do not want the editor to affect the structuring ofyour texts please select "No Indent" at the first cycle gadget.Then there will be no indention after you typed a bracket.On any other selection the cursor will be indented anadjustable amount of characters. You can choose if thisshould happen when typing the bracket or after you hit

StormC User Manual 95

Page 96: StormC V3 Users Manual

5 STORMED◆

<Return> or <Enter>. The values of "Ahead of Brackets"and "Behind of Brackets" will affect the amount ofcharacters ahead of or behind the brackets. You can adjustthe values with sliders or by typing into the string gadget.The range is from 1 to 16.

The value does not always mean single characters because itis effected by the context of the next cycle gadget. If it says"Indent Spaces" it will be real characters. But if it says"Insert Tabs" the cursor takes over the value of "Tab Size".For example: when you set "Tab Size" to 8 and "Ahead ofBrackets" to 4 the cursor will indent 32 characters andinsert a bracket there. If you choose "Insert Spaces" thecursor would be moved 4 characters to the right and thebracket would be inserted here.

The use of automatic indent takes effect only if you activatedthe indent function of the editor. Otherwise the cursor willbe placed in the first column after hitting <Return> or<Enter>.

Indent Brackets When you set the option "Indent Brackets" a bracket willbe set according to the value set at "Ahead of Brackets".An amount of spaces or tabulators will be inserted in frontof the bracket and the cursor will be placed behind it.

Indent behind of Brackets

To activate automatic indent according to "Indent behinda Bracket" you must hit <Return> or <Enter> behind abracket. According to the value of "Behind of Brackets"the cursor will be moved a certain amount of spaces ortabulators to the right. This will be done relative to theposition of the cursor.

For example: when the cursor is in column 10 and you typea bracket the cursor will be placed in the next line in column12 (if you set "Insert Spaces" and "Ahead of Bracket" to2).

Ensure that the Indent function is active for these

settings to take effect. You can check the status by the "I" icon.

Indent ahead and behind of bracketsThe option "Indent ahead and behind of Brackets" isa combination of "Indent Brackets" and "Indentbehind of Brackets". If you type a bracket a certainamount of spaces or tabulators will be inserted. The bracketwill be set and the cursor will be placed behind it. If youenter <Return> or <Enter> afterwards the cursor will be placedin the next line and it will be moved the indicated amount

96 StormC - the professional choice

Page 97: StormC V3 Users Manual

Options of Text◆

of spaces or tabulator to the right. If you enter one or morecharacters instead of <Return> or <Enter> the function will beterminated and after the next input of <Return> or <Enter>the cursor will be placed in the following line just under thebracket.

If all these explanations seem to be confusing, please takesome time to use the functions yourself. This way you willsee that all these settings are actually very simple in use.

Dictionaries and SyntaxText colouring When you chose this settings page you will see two lists of

gadgets. The first group is called "Dictionaries" the second"Syntax".

DictionariesIn this group you will find a list of gadgets to control the useof dictionaries for text colouring. The dictionaries are storedin the drawer "StormC:StormSYS/Dictionary" and youcan load them with the editor.

Pre-processor"Preprozessor.dic"

Here you will find all the defines of constants, that meanseverything that starts with "#define".

C/C++ Symbols"C Symbols.dic"

This dictionary contains the C type-definitions like "auto","sizeof", ...

C/C++ Libraries "C Library.dic"

StormC User Manual 97

Page 98: StormC V3 Users Manual

5 STORMED◆

This includes all ANSI C and C++ standard functions.

AmigaOS Types "Amiga Types.dic"

In this dictionary you will find the Amiga specific types like"ULONG", "STRPTR", ...

AmigaOS Functions"Amiga Functions.dic"

This dictionary contains a list of all names of AmigaOSfunctions.

The following tree entries are for user-defined dictionaries.They do not contain any settings. The files are named "User1.dic", "User 2.dic" and "User 3.dic".

If you activate the functions here the words of the texts inthe editor will be marked in various colours according to thecolour definitions of the dictionaries.

SyntaxOn the right side of the settings page there are controls forfurther colouring of the editor.

C Comments A comment in C begins with "/*" and ends with "*/".Comments might be longer than one row, but the must notcontain further comments. As soon as you type "/*" thefollowing text will be coloured. This will end when you enter"*/".

C++ Comments C++ comments are finite to one row. It will be marked with"//". There is no marker for the end of such a comment.

String Constants The marking of a string constant will start with a characteryou enter with <Shift>+<2>. It will be ended with the samecharacter.

Character Constants Character constants will be marked with a single "‘"(<Shift>+<Ä>).

Number Constants All numbers that are not contained within quotation marksor semi-colon will be coloured by this function.

98 StormC - the professional choice

Page 99: StormC V3 Users Manual

Options of Text◆

Colour SettingsThe settings of colours will be made in the file"StormSettings.ED".

For example: ...

Only the lower 5 rows of this settings file are of interest. Thedefinition has the following setup:

1. foreground colour (RGB)2. background colour (RGB)3. foreground index 4. background index 5. softsyle

The separation into these values has the advantage thatAmigaOS 3.0 and above can use palette sharing. The OSfunction will look to see whether there is the requested (orother suitable) colour it can use. AmigaOS 2.1 and older willuse fixed colour indexes. That is the reason for both methodsused here. If you use AmigaOS 2.0 or older the colour useddepends on the colour settings you made on Workbench.AmigaOS 3.0 and above will try to get the colour yourequested or a colour that is close to this one. The resultmight not be as good as you expect, but this is a commonproblem on computers with only a few colours available.

File Saving Settings

To prevent the saving of text with spaces at the end of somelines you can turn on the function "Strip Blanks At EndOf Line".

StormC User Manual 99

Page 100: StormC V3 Users Manual

5 STORMED◆

Saving the SettingsAll the settings you made will be saved as Tool Types of yourtext. If you want these settings to take effect on every newtext you create you must activate the menu item "Project/Save as Default Icon".

Keyboard NavigationMost of the actions of the editor can be activated by specialkeys. The following paragraphs will give you an overviewabout the keyboard navigation.

Cursor-KeysYou can move the cursor by the use of the cursor-keys andthe regular combinations with <Alt>- and <Shift>-keys.

<Alt>+cursor left / right will move it to the beginning of theword before or after the current cursor position. <Alt>+cursorup / down will move to the beginning or end of the text.

<Shift>+cursor left / right will move to the start or end of theline. <Shift>+cursor up /down will turn over one page up ordown.

<Return>, <Enter>, <Tab>When you hit <Return> and the cursor stands in a text line,the line will be split. When you enter <Return> at thebeginning of a line a spaced line will be inserted before thisline. When you enter <Return> at the end of a line a spacedline will be inserted after this line.

These actions will be the same when you enter <Enter>instead of <Return>.

Using the <Tab>-key will insert 3 spaces or the value you setin the text settings. Using Tabulators will improve thestructure of your source so you can read it better.

Undo / RedoOne of the most important functions of a text editor is thepossibility to undo other functions like editing or deletingtext. Redo is the reverse function of Undo. So if you typed atext and entered "Undo" it disappears. When entering "Redo"it will appear again. StormED offers unlimited Undo/Redo.

100 StormC - the professional choice

Page 101: StormC V3 Users Manual

Block Operations◆

For example:

Type the following small program into the editor window:

while (!sleep)sheep++;

Hit the keys <Right Amiga>+<Z> (this is the same as the menuitem "Edit/Undo"). The text will disappear character bycharacter. Now hit <Right Amiga>+<T> (this is the same asthe menu item "Edit/Redo"). The text will appear again.

Block OperationsWith the help of block operations you can move or copysmall or large parts of your text. These functions are veryimportant in an editor. A block is an area of the text that ismarked. The fundamental block operations are ...

Mark, Cut, Copy and PasteTo execute a block operation you must first mark a block.Choose the menu item "Edit/Mark" and move the cursor.The area between the starting point of the cursor and itscurrent position will be inverted. This shows you that thisarea is marked. All block actions will effect this area only. Ifyou choose the menu item "Edit/Mark" again the markingof the text will disappear.

"Cut" will cut out the marked block of the text and copy itto the clipboard. The block is no longer visible. "Copy" willcopy the marked block to the clipboard. It will remainvisible. "Paste" inserts the contents of the clipboard at thecurrent position of the cursor into the text.

For example:

• Please load a large text file into the editor window. • Move the cursor to the middle of the first line of the text

and choose menu item "Edit/Mark".• Move the cursor down a few lines. You will see an

inverted area of your text.• Choose menu item "Edit/Cut" and the marked block

will disappear. The rest of your text will be moved to fill the free area.

To restore the old text you must paste the clipped block fromthe clipboard to your text. But remember that you should

StormC User Manual 101

Page 102: StormC V3 Users Manual

5 STORMED◆

not move the cursor, because it marks the position for theinsertion of the block. So if you move it, the block will beinserted in a different place.

• Now choose menu item "Edit/Paste". The block will be inserted from the clipboard and your text will return. The cursor will be at the end of the block.

To insert the block at a different place within your text,move the cursor to the desired position and choose "Edit/Paste" again.

When you want to copy a certain block of your text, justmark it and choose "Edit/Copy". The text is not affected,but it is copied to the clipboard.

The MouseUsing the mouse you can move the cursor to any position ofthe text. Just move it to the right place and hit the left buttonof the mouse. As long as you hold the left button down thecursor will follow your mouse-movement and the text willbe marked and inverted. It is the same as using the menuitem "Edit/Mark". When you move the mouse cursor to thetop of the window while pressing the left button, the textwill be scrolled in this direction. After you release the leftbutton of the mouse the block will still be marked until youclick it once more.

Find and ReplaceFind and replace is one of the basics features of any editor.You will get a requester when you choose the menu item"Edit/Find&Replace".

Type the word you are looking for into the first string gadget.If you don’t want to replace it, leave the next string gadgetunfilled and hit the button "Find".

102 StormC - the professional choice

Page 103: StormC V3 Users Manual

Find and Replace◆

DirectionYou can choose the direction for the search from within acycle gadget. You can search "Forwards", "Backwards"and "Whole Text". "Forwards" and "Backwards" willstart from the current position of the cursor. "Whole Text"does not care about the cursor position and looks for yourkey-word through the whole text.

ModeThis option defines how the search word is compared againstthe text.

TextThe key-word will be searched throughout the text. A key-word like "port" would be found in words like "userport"and "ports".

Whole WordThis would only find words that exactly match the key-word.

From Beginning of the Word

This would look for words which begin with the key-word.So "ports" would be found, but not "userport".

From the End of the Word

This would look for words which end with the key-word."Userport" would be found, but not "ports".

From Start of LineThis would only look at the first word of a row.

From End of LineThis would look at the end of the row only.

Ignore Upper/Lower Case This would ignore whether the word is in upper or lowercase.

Ignore Accent This would ignore whether a word contains accents or not.Accents would be treated as they were normal letters. E.g."RenÈ" and "Rene" would be the same.

FindThis starts the search process. If there is no matching wordyou will hear a "display beep".

StormC User Manual 103

Page 104: StormC V3 Users Manual

5 STORMED◆

ReplaceIf you choose "Replace" the function will look at the firstmatch of text and key-word. Then it would replace thismatching text with the key-word and continue the search.

Replace All This would do the same as "Replace", but it would not stopuntil it has searched (and replaced) the whole text.

The "Find&Replace" requester will stay open as long as youare working with it. This is a non-modal requester. You canalways close it with the close gadget or by hitting <ESC>-key.

104 StormC - the professional choice

Page 105: StormC V3 Users Manual

Compiler6 ◆

6 Compiler

espite computers are getting faster and faster you do not want to forego ona fast compiler. This does not only mean speed at compiling but speed,which benefits through used optimisation to speed up programs.

StormC offers both in an excellent way. It is a very fast compiler with outstandingoptimisation. C++ sources will be compiled to machines-code in one pass. Pre-compiledheader care for tremendous compiler speed at large projects.

You will learn more about special features of StormC in this chapter.

SPECIAL FEATURES OF STORMC ................................................................. 107

DATA in Registers ........................................................................................ 107

Parameters in Registers ............................................................................ 108

Inline Functions ............................................................................................ 108

The Pragma instructions .......................................................................... 110Data in Chip and Fast RAM .............................................................................. 110AmigaOS Calls .................................................................................................. 111The #pragma tagcall ........................................................................................ 111

The #pragma priority ................................................................................ 112Constructors and Destructors in ANSI C ........................................................... 113Constructors and Destructors in C++ ............................................................... 113Priority list ........................................................................................................ 113

Joining Lines .................................................................................................. 114

Predefined symbols .................................................................................... 115

Build your own INIT_ and EXIT_ routines .......................................... 117

Use of Shared libraries .............................................................................. 117Prototypes ........................................................................................................ 117Stub Functions .................................................................................................. 118#pragma amicall .............................................................................................. 118Forced opening of a Amiga library ................................................................... 122

PROGRAMMING OF SHARED LIBRARIES .................................................. 123

The Setup of a Shared Library ................................................................ 123The #pragma Libbase ....................................................................................... 124Register Setup ................................................................................................... 124

D

StormC User Manual 105

Page 106: StormC V3 Users Manual

6 COMPILER◆

Shared Library Project Settings .........................................................................125The setup of FD files ..........................................................................................125The first four Functions .....................................................................................126Home-made Initialisation and Release ..............................................................127Important hints to Shared libraries ...................................................................128

PORTING FROM SAS/C TO STORMC ......................................................130

Project settings ............................................................................................130

Syntax ...............................................................................................................131

Keywords .........................................................................................................131

CLI VERSION OF THE COMPILER .................................................................134

The instruction .............................................................................................134

Options ............................................................................................................134Assembler source ...............................................................................................136Pre-processor: Definition of symbols .................................................................136 Pre-processor: Include files ...............................................................................137

Compiler mode .............................................................................................137ANSI C or C++ ..................................................................................................137Exception handling ...........................................................................................137Creation of Template functions .........................................................................138

Code creation ................................................................................................138Data model .......................................................................................................138Code model .......................................................................................................138Optimisations ...................................................................................................138Code for special processor ................................................................................140Code for linker libraries .....................................................................................141

Debugger ........................................................................................................141RunShell ............................................................................................................141Symbolic debugger ...........................................................................................141

Copyrights ......................................................................................................141

Warnings and errors ..................................................................................141Format of the error output ................................................................................141Colours and styles .............................................................................................142Error file ............................................................................................................142Optional warnings ............................................................................................143Treat warnings like errors .................................................................................144Core memories ..................................................................................................144Pre-compiled header files ..................................................................................144

Summary .........................................................................................................145

106 StormC - the professional choice

Page 107: StormC V3 Users Manual

DATA in Registers◆

SPECIAL FEATURES OF STORMC

DATA in RegistersEach processor manages not only the RAM, but has inaddition also some internal processor registers, in which itstores results of calculations and so on. The access to theseregisters is considerably more quicker than a RAM operation.Since the processors of the 68000-family are richly equippedwith registers programmers will take the unused registers toarchive often used variables into them to increase speed.

Fortunately you has introduced a flexible and machine-independent notation for it in the ANSI C standard. The keyis a memory class named "register", which can be usedanalogue to "extern", "auto" or "static".

Register variables may be declared only within functions.Otherwise you can use them freely: You may declare as manyvariables as you want form different types as "register",the compiler decides later on which files to store in a register.Integer and pointer or reference variables may be put intoregisters, whereby numeric types are stored in data andpointer types in address registers.

However you should be careful not to use registers tooextensively because the processor will need at least oneregister for practically all operations. When you are using toomany of them for variables it must evacuate them sometimesfor a short time on the stack and load them later again. Thenyou can not expect an increase in speed. As a rule you shouldnot use more than four integer and two pointer variables as"register" in one function.

StormC does not use your statements obligatorily. Indeed ittakes them only as reference. The optimiser of StormC candecide essentially better, which variable to which time inwhich register is to be loaded best. Furthermore StormC usesthe registers repeatedly in a function, which you can notmake by using the key-word "register".

StormC User Manual 107

Page 108: StormC V3 Users Manual

6 COMPILER◆

Parameters in RegistersThis does not corresponds to C++ standard!

You should insert this feature therefore as carefully as possible, since the programs are otherwise no more portable. It is best to use such parameters only, if you want to bind finished functions, which expect their arguments in registers, to a program. E.g. the AmigaOS functions or assembler routines, which can be ported badly anyway.

As small expansion of the C++ standard StormC offers thepossibility to also submit parameters in registers. Sometimesthis leads to certain speed increases. You simply have towrite the symbol "register" before the parameters of thedeclaration of the function, e.g.

int Inc (register int i, register int j);

There are even two possibilities to prescribe the compiler inwhich registers it should put the parameters: Either yourename the parameter variable as a 68000 register, e.g.

void f(register int d0, register char *a2)…

or you set the desired register name with "__" behind thekey-word "register"

void f(register __d0 int i,register __a2 char s)…

If you are instructing the compiler this way which registersit should use for variables you should consider previouslyabout the things you are doing there.

For your own C++ functions this feature is absolutely taboo,because you don’t know whether the above declaredfunction would become possibly very slow because it needsthe register "d0" constantly but it must store and restore thecontent of the registers variable every time. You should usesuch register regularise for declaration of imported assemblerand system functions only.

Inline FunctionsEach function call represents a considerable expense. Firstthe calling code must arrange some space for the argumentson the stack and store them there. Then a "JSR" jumpfollows into the function, which has to reserve the necessarymemory for their own data on the stack before. And it has tostore the contents of all processor registers, which arechanged by it. At the end of the function the old registercontents are restored again. The local variables are removedfrom the stack; a "RTS" jump back to the calling program isfollowing. At least the arguments must be taken from thestack. There you as programmers might get into moralconflicts: Should you define a small function now or insert

108 StormC - the professional choice

Page 109: StormC V3 Users Manual

Inline Functions◆

the content of this function every time into the program? Atypical example is the maximum function:

int max(int a, int b){ if (a>b)

return a;elsereturn b;

}

Instead of the function call "max(x,y)" you could as analternative insert "(x>y ? x : y)" each time. This wouldbe of course more quicker, but not more readable. For suchcases C++ has a nice feature that StormC now offers in ANSIC mode as well: "Inline" specification.

If you set the key-word "inline" (in ANSI-C "__inline")before the first declaration of a function, this functiondefinition will be inserted into the source at each time thisfunction is called. Syntactically or semantically the programis not changed thereby: You declare simply

inline int max(int a, int b) { if (a>b)

return a;elsereturn b;

}

Then you can use "max" like a normal function. Thedifference lies solely in the generated code. With "inline"the content of "max" will be copied every time into thecalling code.

A lot will be saved thereby: There must neither be a "JSR"into the function nor a "RTS" back. There must be no storingand restoring of the contents of registers. The function mustnot arrange its own data "frame" on the stack. The result notgiven back in register "d0". * And the compiler will still havemany possibilities for optimisations.

An inline function is not created once only, but in manycopies, for each call a separate one. It is obvious that"inlining" will blow up programs tremendously and youshould use it carefully. The compiler however may ignorethat "inline".

StormC User Manual 109

Page 110: StormC V3 Users Manual

6 COMPILER◆

StormC handles this in a better way: what you want to be"inlined" will be "inlined". Still there can be situations,in which an inline must be created on completely usuallymanner, e.g. if you take the address of a such function if it isused already before it was declared if an inline function isrecursive.

All this is allowed because you can use an inline functionexactly as each other function.

If an inline function is created of one the above reasons, itnaturally has internal linkage. So other modules will notnotice whether the function was actually generated in acompiler. Therefore similar instructions like for the memoryclass "static" will apply for "inline". The declarationsequence

inline void f(); void f();

is allowed,

void f();inline void f();// ERROR

is not allowed. By the way inline is not a memory class (like"static" or "external"), but a "functionspecification".

The Pragma instructionsDespite the ANSI specifications each compiler has its ownpeculiarities. These specific things are introduced with thekey-word "#pragma".

"#pragma" lines will be interpreted by the pre-processor like"#include" lines. With "#pragma" you can realise compilerspecific functions, which are not standardised explicitly.

Compiler mode "#pragma -" is a non-standard featureswitches StormC into ANSI C mode.

"#pragma +" switches the compiler to translate the sourcein the C++ mode.

Data in Chip and Fast RAM The architecture of the Amiga is somewhat unorthodox. Sothere are two or sometimes even more different types of

110 StormC - the professional choice

Page 111: StormC V3 Users Manual

The Pragma instructions◆

RAM. Normally programmers are only interests in using"Chip- or Fast-RAM" because they must care for thatgraphic data are stored in chip memory. StormC thereforeoffer the pragmas "chip" and "fast".

All after the line

#pragma chip

declared static datas will be loaded into Chip RAM,

#pragma fast

switches back to normal mode. Now data will be storedsomewhere, however Fast RAM is the preferred place.

AmigaOS CallsThe AmigaOS functions are called with the #pragma amicall.This declaration exists in the essential of four parts:

• The name of the basis variable.• The offset as positive integer. • The function name, which must be declared already. For

reasons of the definiteness this function name may notbe overloaded.

• The parameter list, represent through a correspondingamount of register names in parenthesis.

An example:

#pragma amicall(Sysbase, 0x11a, AddTask(a1,a2,a3)) #pragma amicall(Sysbase, 0x120, RemTask(a1)) #pragma amicall(Sysbase, 0x126, FindTask(a1))

Normally you will never have to write such declarations byyour own, since everything is included within the Amiga-Libraries.

The #pragma tagcallAt some OS calls so-called TAG lists will be submitted asfunction parameters. These are not really OS functions butSTUB functions, which are declared with ellipse. You areusing these functions, since the submission of TAGs asfunction parameters is to be programmed very simply. Theuse of an array would be of course be a good way too, but itcauses more work on typing.

StormC User Manual 111

Page 112: StormC V3 Users Manual

6 COMPILER◆

An example:

The pragma definition of the function "CreatGadgetA()"from the Gadtools-Library looks as follows:

#pragma amicall(GadToolsBase, 0x1e,CreateGadgetA(d0,a0,a1,a2))

#pragma tagcall(GadToolsBase,0x1e,CreateGadget(d0,a0,a1,a2))

You find the corresponding prototype in the drawer "CLIB".They contain the following:

struct Gadget *CreateGadgetA(unsigned long kind,struct Gadget *gad, struct NewGadget *ng,struct TagItem *taglist);

struct Gadget *CreateGadget(unsigned long kind,struct Gadget *gad,struct NewGadget *ng,Day tag1, …);

With the call

gad = CreateGadget(CYCLE_KIND, gad, ng, GTCY_Labels, mlabel, GTCY_Active, 3, TAG_DONE);

you would "so to speak" inline create a Stub function, whichpushes all Tags on the stack but in reality calls the function"CreateGadgetA()".

For compatibility reasons the most pragma calls of the SAScompiler can be used too.

The #pragma priorityStormC supports as a C++ compiler the automatic call ofinitialisation and exit functions before and after call of"main()" function.

Whether stdio will be initialised or not will not

depend on startup-code, but if the program uses printf() or similar I/O functions.

C++ uses this feature to call the constructors and destructorsof global variables. ANSI C uses this feature for the automaticopening of shared libraries or for the initialisation ofstandard I/O.

The function table, which is processed thereby, is createdfirst through the linker. Functions, which own a certainname, will be gathered by the linker to a table of

112 StormC - the professional choice

Page 113: StormC V3 Users Manual

The #pragma priority◆

initialisation and exit functions. The startup-code must callthe function "InitModules()" before the call of "main()"function and to call "CleanupModules()" after "main()"function.

The advantage of this dynamic concept is the flexible setupof the startup-code. The resulting program is always as smallas possible. The thereby available startup-code is applicablefor all programming projects. The large-scale and error-susceptible selection of a startup-code according to compileroptions is not necessary any more.

Constructors and Destructors in ANSI CFunctions that are called at initialisation must be named"INIT_n_anything(void)", the exit function must becalled "EXIT_n_anything(void)". For n is a numberbetween 0 and 9. This sets the priority of the function. Thesmaller the value the earlier the initialisation and the laterthe exit function will be called. "Anything" can be replacedthrough each arbitrary name, which may contain further"_".

Constructors and Destructors in C++A C++ compiler creates automatically such fitting functionsfor each global variable. In these functions the constructionand destruction of variables will take place. Generally thecompiler uses the priority 8 for these "INIT_" and "EXIT_"functions.

However the exact sequence of the calls, that means thepriority of the "INIT_" and "EXIT_" functions, may be ofimportance so there exists that "#pragma priority". Youcan determine the priority of the global variable of themodule.

Priority listThereby you should orient yourself on the following list ofthe priority. This tells you the use of the priorities in"storm.lib":

Priority 0:This priority is reserved for functions, which initialise theStormC library (particularly data structures of the library). Ifyou want to initialise a data structure (e.g. a jump table), thatdoes not access to any OS resources, you should use priority0 also.

StormC User Manual 113

Page 114: StormC V3 Users Manual

6 COMPILER◆

Priority 1: The most important shared libraries are opened:

"dos.library" version 37, "utility.library" version 37.

Priority 2: All shared libraries, which are necessary for the function ofthe program, are opened. The program is aborted, if theopening fails. Here all libraries are listed, which are deliveredsince AmigaOS V2.04 (V37).

Priority 3: Here all libraries are listed which are delivered sinceAmigaOS V38 or later or these that do not belong to standarddelivery of the system. You do not know whether theselibraries exist the concrete system. These libraries are openedwith the minimal version. If the opening should fail itoutputs no error message.

Priority 4: With "malloc()" or "new" reserved memory will be freed.

Priority 5: Further library resources are reserved and freed, e.g. globaland temporary files.

Priority 6: There are some cleanups before the resource are freed, e.g.flushing of file buffers etc.

Priority 7: Unused, free for usage.

Priority 8: Constructors and Destructors C++ cases are set to thispriority by default. Each global variable, whose type has aConstructor or a Destructor, creates a call of an "INIT_" or"EXIT_" function. The priority can be changed by "#pragmapriority".

Priority 9: The functions, which were announced with "atexit()", arecalled.

Joining LinesIt is absolutely alike in C and C++ where individual lines end.But the pre-processor must get each instruction exactly inone line. Naturally there will be the case that a line becomesvery long, e.g. through an extensive macro definition. Forthis case there is the backslash. If the is a "\" at the end of aline this is joined with the following one.

For example:

#define SOMETHING \ 47081115

114 StormC - the professional choice

Page 115: StormC V3 Users Manual

Predefined symbols◆

This is a valid macro definition, for "47081115" is pulled herein the preceding line.

Predefined symbols The pre-processor has many predefined macros. Some ofthem are ANSI C standard others are elements of C++ orparticular peculiarities of StormC. These macros can not beredefined.

__COMPMODE__

It is defines with the "int" constant "0" in C mode and "1"in C++ mode.

__cplusplus

StormC defines the macros "__STDC__" in C and C++ mode.If you wants to check, whether if compiling in StormC isdone in C++ mode this must be made with the macro"__cplusplus".

__DATE__

The macro "__DATE__" delivers the date of the compilation.This is very useful, if you want to give a program an uniqueversion number:

#include <iostream.h>

void main() { cout « "version 1.1 from that " __DATE__", "__TIME__" clock\n"; }

The date has the format "month day year", e.g. "Mar 18 1997"and time of day will be "hour:minute:second".

__FILE__

This macros contains the name of the current source file asa string, e.g.

#include <stream.h>void main() { cout « "That stands in line " « __LINE__ « " in file " __FILE__ ".\n";}

StormC User Manual 115

Page 116: StormC V3 Users Manual

6 COMPILER◆

The value of the macro "__FILE__" is a constant string andcan be joined with other strings standing before or behind it.

__LINE__

The macros "__LINE__" delivers the line number, in whichit is used, as decimal "int" constant.

__FUNC__

The macro "__FUNC__" delivers the identifiers of thetranslated function (Aztec compatible) in ANSI C mode. InC++ mode it delivers the qualified function name along withthe parameter list.

__STDC__

This macros delivers in all ANSI C compatibleimplementations the numerical value 1. This should tell youwhether the compiler supports this standard. Otherwise"__STDC__" is not defined.

__STORM__

You may want to know which compiler and version one isusing. Therefore StormC defines the macros named"__STORM__".

__TIME__

(see "__DATE__")

116 StormC - the professional choice

Page 117: StormC V3 Users Manual

Build your own INIT_ and EXIT_ routines◆

Build your own INIT_ and EXIT_ routines If you are writing your own "INIT_"- and "EXIT_" functionsyou should be aware that a call of the function "exit()"from an "INIT_" function will call all "EXIT_" functions.

There is no allocation between "INIT_" and "EXIT_"functions, this means that there is no "INIT_" function thatbelongs to a certain "EXIT_" function with the same name.That applies for each global variable in C++ also. That means,that a destructor must work well even if the matchingconstructor was not processed. You can exploit thereby, thatthe memory of the variable is initialised always with 0, if youhave not changed initialisation. Now you can decide simply,whether the constructor of the destructor was processedalready or not.

Particularly in C++ you should avoid that constructors ofglobal variables do an exception because they can not beenclosed with a Try-block. Therefore this exception is alwaystreated as unexpected exception, which leads to a hardinterrupt of the program and the user will not know why theprogram does not work.

Use of Shared libraries The AmigaOS is essentially built of several shared libraries.These "divided libraries" offer functions which can be calledby each program after opening them.

To each shared library of the AmigaOS there are some Cheaders, which allow the use of the library.

Prototypes First there is the file with the prototypes of the functions.You will find them in the directory "StormC:include/clib". The files are named like "exec_protos.h", that is thename of the library (here: "exec" for the library"exec.library") with appended "_protos.h".

These prototypes define C functions, which are always calledby the compiler in the way that it puts the parameters of thefunction on the stack and makes a subroutine call at thematching function. This function must always be linked tothe program. Therefore it is not allowed to call the sharedlibrary directly because shared libraries are not linkedpermanently to the program, but are opened at the start of

StormC User Manual 117

Page 118: StormC V3 Users Manual

6 COMPILER◆

the program. Besides functions of shared libraries alwaysexpect their parameters in CPU registers and not on thestack.

This problem can be solved on two ways. Either you use Stubfunctions or the special Amiga-like "#pragma amicall".

Stub Functions The linker library "amiga.lib" contains a so-called Stubfunction for every function of the OS libraries. The stubfunction takes the parameters from the stack, loads theminto the right CPU registers and then calls the right functionof the shared library.

This method has the disadvantage of an additional functioncall, which swells your program and decreases the executionspeed strongly.

#pragma amicall Alternative to stub functions you can use "#pragmaamicall" which differs for every compiler. There are thefollowing two methods:

There is a file to each library which describes the calling ofeach function of a shared library. Which parameter must bewritten into which CPU register is explained particularly.The compiler now can call the shared library functionsdirectly without the use of "amiga.lib" .

To get a good comparability with SAS/C and

other compilers there exists a drawer named "StormC:include/pragmas". It contains files which have different file names than these of "StormC:Include/pragma".

These files can be found in the directory "StormC:include/pragma" and they are named like "exec_lib.h" (name of thelibrary with appended "_lib.h"). These files will load theprototypes from "StormC:include/clib" automatically, so one"#include" of the pragmas will be enough.

You can tell the prototypes to load pragmas as well. That ispractical, if they have an older source, which uses only theprototype and contains no includes for pragmas. For this thepre-processor symbol "STORMPRAGMAS" must bedefined. You can define the symbol simply in the compilersettings on "Pre-processor".

118 StormC - the professional choice

Page 119: StormC V3 Users Manual

Use of Shared libraries◆

In this context one says "pragma files" or

"the compiler XYZ knows Pragmas". That is very inaccurate, for the instruction #pragma has nothing to do with the call of shared libraries, for it is ANSI C standard. Indeed "#pragma amicall" is very important and older compilers on the Amiga knew this "#pragma" only. Therefore "#pragma" has become the generalised expression for the direct call of shared libraries.

Furthermore nearly every library has at least one include filewhich describes the data structures which are required forthe library.

Example:

#include <pragma/exec_lib.h> #include <exec/tasks.h> #include <stdio.h>

void main(){struct task *me = FindTask(NULL); printf("The structure has address %p.\n",me); }

This program uses the function "FindTask()" of"exec.library" to get a pointer to the control structure ofthe task and it outputs their memory address.

The "exec.library" has a particularity to all other libraries.It will not be opened by the program, because it is alwaysopen and the functions can be used immediately.

This is different if you have a look at e.g. "intuition.library".

Example:

#include <pragma/exec_lib.h> #include <pragma/intuition_lib.h> #include <exec/libraries.h>

external struct Library *intuition base;

void main() { if((intuition base =OpenLibrary("intuition.library",37)) != NULL)}

DisplayBeep(NULL);CloseLibrary(intuition base);};

};This program makes nothing than flashing the screen.Maybe it will play the 9th Symphony of Beethoven too if youhave reconfigured system beep.

StormC User Manual 119

Page 120: StormC V3 Users Manual

6 COMPILER◆

To get it doing this you must open "intution.library"version 37. That means that you must have at least AmigaOS2.04 installed. The function "DisplayBeep()" is called andthe library will be closed at the end.

You have to not three things thereby:

1. Use the right version number because the compiler cannot recognise whether you open library version 37 butused a function available from version 38 or later. Thiswill crash a computer running an older operating system.

2. Only call functions from those libraries that you reallyopened before. Several reasons can prevent opening:There is no library on the computer with the indicatedname or it exists one with a smaller version number. Orthere is not enough free memory. And there are stillmany other reasons!

3. Close the library at the latest at the end of the program.For only then the library can be removed from memoryagain if AmigaOS need it (presupposed no other programuses this library at the same time!).

A further example:

#include <pragma/intuition_lib.h>

void main() {

DisplayBeep(NULL); };

This program will run too, presupposed you have linked itwith "storm.lib".

Hmm? - did not we just say that you should open librariesbefore use. Yes, you should and that is exactly what thisprogram is doing.

Since StormC is a C++ compiler too there are possibilities toautomatically call functions from libraries on request at theprogram start and end. The library "storm.lib" containssuch functions, which open and close a library on request.This means whenever you are calling a function of a speciallibrary it will be open automatically and closed at the end ofthe program. The linker library "storm.lib" knows all OS

120 StormC - the professional choice

Page 121: StormC V3 Users Manual

Use of Shared libraries◆

libraries up to version 39. Thereby two different strategies arepursued how to treat a failure at opening:

1. Libraries of Kickstart version 37 are opened with just thisversion and cause an error message and cancellation ofthe program, if the opening fails.

2. Libraries of later OS versions (e.g. "locale.library")are opened with the smallest version (here"locale.library" version 38) and the program iscontinued when the library can not be opened.

You are responsible for calling no functions which are notavailable on the used OS and you must not call functionsfrom libraries which could not be opened.

The following two code fragment will help you testing this:

#include <exec/libraries.h> #include <graphics/ratsport.h>#include <pragma/graphics_lib.h> #include <graphics/gfxmacros.h>external struct Library *GfxBase;

void setoutlinepen(struct RastPort *rp, ULONG pen) { if(GfxBase->lib_Version >= 39)//min. OS 3.0{ SetOutlinePen(rp,pen) }

else{ SetOPen(rp,pen); };

};

This code distinguishes between AmigaOS 3.0 and olderversions to set the pen number for the borders correctly.Older OS version have a macros for this only but as from V39there exists a function.

StormC User Manual 121

Page 122: StormC V3 Users Manual

6 COMPILER◆

The printed listing is not a real program,

since the main() function is missing. If you want to try this function simply make an own main() function for it.

#include <libraries/locale.h> #include <pragma/locale_lib.h>#include <exec/libraries.h> external struct Library *LocaleBase; char yday[80];

STRPTR yesterday(){ STRPTR retval = NULL;if (LocaleBase != NULL){struct Locale *locale = OpenLocale(NULL);if (locale){STRPTR s = GetLocaleStr(locale,YESTERDAYSTR);if (s){strcpy(yday,s);retval = yday;};

CloseLocale(locale);};

};if (retval == NULL)retval = "Yesterday";

return retval;}

This function delivers the string "Yesterday" of thenational language chosen at local settings or "Yesterday" ifsomething goes wrong. If you are running AmigaOS 2.04 itis to be foreseen that the program does not deliver thedesired result because locale library is provided withAmigaOS 2.1 (V38) first.

Surely it is not skilful to open and close locale

structure every time but we want to show the principles.

Forced opening of a Amiga libraryIf you really want to force opening of the library in a higherversion (e.g. "graphics.library" version 39) or if you wantto open it anyway there exists of course the possibility toopen and close the library "by hand". Indeed you shouldnote that you have to declare the basis pointer variable (e.g."struct library *GfxBase"). Otherwise the automaticopening mechanism comes into confusion. You can use theautomatic opening mechanism as well and test the"main()" function at the beginning and terminate theprogram when required.

122 StormC - the professional choice

Page 123: StormC V3 Users Manual

The Setup of a Shared Library◆

PROGRAMMING OF SHARED LIBRARIES The creation of an own shared library can be very useful. Assoon as several programs use equal code or some functionsshould be available to other programs or programmers it ismeaningful to build a shared library instead of using acollection of functions.

StormC supports you at this task so you must not care abouttechnical details. The creation of a shared library will not bemore expenditure than a building a linker library.Nevertheless you should know about the setup of a sharedlibrary to avoid some possible errors and to use StormCoptimally.

The Setup of a Shared Library A shared library exists essentially of a basis structure(therefore at least a "struct library") and a function table,in which each function of the shared library has an entry.Besides each shared library has a version string, which youcan query with the command "version" from the CLI.

The basis structure is at least one "struct library" but youcan add further elements. That is meaningful if theprograms, which use the shared library are accessing onsome data without having to call a library function.

You should progress to the rule to use public data verysparingly, for the accesses through other programs, whetherreading or writing can not be record in the library. You mustalso pay attention in future versions of the library that thesedata will keep the same sense, which is not always toosimple.

It is safer and more simple for you to hold the data of thelibrary in normal global variables. The access should be by afunction, even if these are only very small functions, whichdeliver the value of a variable. The "dos.library" uses thisprinciple intensely since AmigaOS version 36 e.g. to makeaccessing of structure more save.

StormC User Manual 123

Page 124: StormC V3 Users Manual

6 COMPILER◆

The #pragma Libbase The name of the basic structure must be told the compiler ata position in the source. This will be done with "#pragmalibbase".

If you have divided your library in several

modules #pragma libbase should be called in one source only.

For example:

#include <exec/libraries.h>

struct MyLibBase{struct Library library;ULONG second_result;

};#pragma libbase MyLibBase;

Register Setup The functions of a shared library receive their argumentsfrom a CPU registers, data like "int", "LONG", "char" etc. indata registers ("d0" to "d7") and pointers in address registers("a0" to "a5"). You should count data register starting from"d0" and address registers starting from "a0". But youshould forego "a5" since this register is used by almost everyC function to set up a so-called "stack frame". If a sharedlibrary uses "a5" as a parameter you will probably getproblems when a function is called by "#pragma amicall".In this case you should write a stub function for this functionin assembler and forego the "#pragma" call.

Despite this restraint the address registers "a0" to "a4" areavailable and that should suffice for nearly each function.

To be able to access to entries of the basis structure, a pointerto the basis structure in register "a6" must be indicated as aparameter. This parameter is set automatically at the call ofa function of the shared library.

An example:

ULONG add_two(register __d0 ULONG a,register __d1 ULONG b,register __a6 struct MyLibBase *base)

{ ULONG retval = a + b; base->second_result = retval; return retval;

};

124 StormC - the professional choice

Page 125: StormC V3 Users Manual

The Setup of a Shared Library◆

Shared Library Project Settings To create a shared library you must create a new project,which contains of at least one source code with some ANSIC functions, a FD file, which describes the register use of thefunctions and an entry for the program name, which alwayshas the ending ".library".

In the settings of the project you choose at the page "C/C++options" "Large Data Model" and at "Linker Options1" naturally "Link As Shared Library". Besides you candetermine the "version" and "revision" of the library."Linker Options 1" has two fields for this.

The setup of FD files The FD file looks as follows: their name always uses the suffix".fd", so it is placed in the right section ("FD files") of theproject. "FD" or ".fd" stands for "function description").

The file is composed of individual lines, which begin eitherwith a "*" (commentary) or with a "##" (special command).Otherwise the line must contain a valid functiondescription.

Example:

##base _MyLibBase##bias 30 ##public add_two(a,b)(d0,d1) ##end

The command "##base" marks the name of the basisvariable, whereby the name is indicated as linker symbolwith leading "_". In your C program you will write thisvariable without the leading "_" character.

The command "##bias" sets the offset of the function. Inthe function table the functions are standing one afteranother. The first function has the offset -6, the nextfunction the offset -12, the third the offset -18 etc.

With "##bias" you can set this offset newly, indeed you willgive them positive values. Each function increases thepositive offset with 6, for in the function table stands a "jmpxxx.L". That is a assembler instruction which jumps at thereal beginning of the function. This assembly instruction

StormC User Manual 125

Page 126: StormC V3 Users Manual

6 COMPILER◆

requires just 6 byte. Normally you sets this "##bias" on 30,for the first 4 functions are reserved.

The command "##public" marks the following function aspublicly accessible. The command "##private" not used inthe above-mentioned example marks the followingfunctions as private.

The command "##end" terminates the function description.Everything that follows in the file will be ignored.

Before the command "##end" stand the functiondescriptions. These exist respectively of the name of thefunction, the name of the parameters (which are commaseparated encircled by brackets) and finally the list ofregisters. Every parameter is associated with one register. Theparameter of the register a6, which you may have indicatedin your ANSI C function, is not indicated here.

The function description increases "##bias" automaticallyat 6. You do not have to set "##bias" newly after eachfunction.

Restraints Under StormC there is momentarily a restraint.The command "##bias" can be used no more after the firstfunction description. Theoretically it is possible, to create anot coherent function table in the FD file, e.g. because thefunction table contains functions, which should be invisibleto the user. Since the FD file should be used for the creationof a function table it must be coherent.

The first four Functions Just one word to the reserved first 4 functions. Thesefunctions are called "LibOpen()", "LibClose()","LibExpunge()" and "LibNull()". To it comes thefunction "LibInit()", which is not called over an entry ofthe function table.

The function "LibInit()" will be called and initialised afterloading, therefore at the first open of the library. That meansparticularly at StormC, that the automatic constructors orinitialisation functions are called, which will e.g. open otherrequired libraries. That works equal to normal programs, soyou must not care for the correct initialisation. For C++programmer the constructors of the global variable are calledtoo.

126 StormC - the professional choice

Page 127: StormC V3 Users Manual

The Setup of a Shared Library◆

The function "LibOpen()" is called at each opening and itdoes nothing than to record just this fact. It increases acounter which indicates how often the library was opened.

The function "LibClose()" is called when closing thelibrary and it decreases the counter.

The function "LibExpunge()" is always called when theoperating system wants to remove the library from memory.That happens for example at memory shortage. The librarycan be removed only if it was not just opened by a program.The counter must stand on 0, so you will note howimportant it is to close used libraries. A task of the function"LibExpunge()" is to call the automatic destructors or exitfunctions. Thereby e.g. the automatically opened librarieswill be closed again. At use of C++ the destructors of theglobal variables will be called.

The function "LibNull()" does nothing at all and it isreserved for future extensions.

These five functions are in the linker library "storm.lib".You can overwrite them at any time with your ownfunctions. Probably you will have to use an assembler forthis. A meaningful and also in C feasible expansion wouldbe e.g. to overwrite the function "LibNull()" through afunction which makes the library useful for ARexx. How thiswill function you must read in suitable literature.

Home-made Initialisation and ReleaseJust because you want to execute additional tasks at loadingof libraries or when removing them from memory (e.g. theopening of further libraries or memory reservations), that isno reason write the functions "LibInit()" and"LibExpunge()" new. Simply use the possibility toimplement automatic initialisation or exit functions.

If you are using C++ you can do this with global variables,whose type owns a constructor or a destructor. These will becalled automatically in "LibInit()" or "LibExpunge()".The execution sequence can be determine with "#pragmapriority" more closely.

Using ANSI C you can simply name the functions as thelinker expects it to call it automatically. An initialisationfunction must be named "INIT_n_anything(void)" and an

StormC User Manual 127

Page 128: StormC V3 Users Manual

6 COMPILER◆

exit function "EXIT_n_anything(void)". Whereby "n" is anumber between 0 and 9. This number determines thepriority of the function. The smaller the value, the earlier theinitialisation function and the later exit function is called.

Example:

struct Library *DOSBase;struct Library *intuition base;

INIT_3_OeffneBibliotheken(void){ DOSBase = OpenLibrary("dos.library",37);

Intuition base =OpenLibrary("intuition.library",37);

}

EXIT_3_SchliesseBibliotheken(void){

CloseLibrary(intuition base);CloseLibrary(DOSBase);

}

Beside these standard functions a shared library still requirescertain tables and data structures, which initialise the sharedlibrary at start. These are situated at the startup code"library_startup.o", which is used at "linker asshared library" automatically. This startup code usessome symbols, which are created by the linkerautomatically. Among other things a symbol on thebeginning of the function table and one symbol on thename of the library and the version string of the library. Thetwo last symbols can overwritten. They are called"_LibNameString" and "_LibVersionString".

Important hints to Shared libraries Here a couple of hints for the development of your ownshared libraries.

First develop you functions completely normal and write atest program for them. If everything functions to yoursatisfaction, transform the project to a shared library, byremoving the test program from the project and write asuitable basis structure. Of course some project settings mustbe changed too.

128 StormC - the professional choice

Page 129: StormC V3 Users Manual

The Setup of a Shared Library◆

You have won two advantages by this way: Shared librariesmust be removed from memory before you can exchangethem by a newer version. Therefore you must care that yourtest program has closed the shared library and that the oldlibrary is removed by executing "avail flush" from theCLI. That is much complicated than to simply start the newprogram. Besides you can not debug in shared libraries.

Pay attention that your functions are "re-entrant". Thatmeans that several programs can use it simultaneously. Thatforbids in general the use of global or static local variables tostore interim results. If you want to receive data over severalfunction calls you must work in the certain "object-oriented"way. You know that from "intuition.library": You opena window and get back a "struct Window *". With thispointer you can manipulate the window now, until youclose it. Then "intuition.library" receives this pointer ateach function call and can work with the data structure.Thereby you avoid global variables.

A shared library should not need to use large stack

size.

If you need much data locally (e.g. for a large array) youoften use static local variables in "normal" programs. Inshared libraries you should lay these variables on the stackand if required previously accomplish a "StackSwap()" orstore the data short-term in the dynamic storage, reservedwith "AllocMem()". The third possibility is to protect witha semaphore the simultaneous use of the static variablethrough several programs. Which method you chooses is aquestion of the respective situation.

StormC User Manual 129

Page 130: StormC V3 Users Manual

6 COMPILER◆

PORTING FROM SAS/C TO STORMCWe have made it a point to equip the StormC compiler withmany important properties of the SAS/C compiler, ie.support for various SAS-specific keywords and #pragmas.Nevertheless there may - depending on your programmingstyle - be large or small amounts of trouble when portingsoftware from the SAS/C compiler to the StormC compiler.

Please keep in mind that StormC is an ANSI-C and C++compiler. SAS/C on the other hand is a C and ANSI-Ccompiler (the C++ precompiler is not likely to have foundmuch serious use), meaning that it understands a lot of oldersyntax that StormC will not accept. This is likely to causetrouble when migrating your sources to StormC, unless youare used to compiling your SAS/C programs strictly inANSI mode (using SAS/C’s ANSI option).

Project settingsFirst of all make sure that the project you build around yourSAS/C sources is in ANSI-C compiler mode.

Try enabling as many warnings as possible, and then adaptyour programs until no more warnings are given whencompiling. This will give you the best chance that yourprogram will do exactly what you intend it to.

Even for pure ANSI-C projects, switching to C++ later isrecommendable. This will have several advantages:Prototypes are expected for all functions, and implicitlyconverting a void * to another pointer type is no longerlegal.

Although this may necessitate a relatively tiresome rework ofyour programs (especially the latter change which affects agreat deal of statements that call malloc() or AllocMem()),but can give you a great deal more confidence in thecorrectness of the program.

The long symbol names in C++ provide additional securitywhile linking: If a function definition is in any wayinconsistent with its prototype declaration, the linker willabort with reports of an undefined symbol.

Switching to C++ will also give you the possibility to extendyour program with modern object-oriented concepts, as well

130 StormC - the professional choice

Page 131: StormC V3 Users Manual

Syntax◆

as the use of several smaller C++ features (such as the abilityto declare variables anywhere in a statement block).

SyntaxSome SAS/C keywords are not recognized by StormC, othersare supported well, but the more "picky" StormC compileronly allows them in the typical ANSI-C syntax.

StormC does accept anonymous unions, but not implicitstructs. Equivalent structures are not considered identical. Ifyou have made use of this feature, you will need to insertcasts in some places.

If this feature is important to you, you may want to considermoving your project over to C++: Equivalent structs arenothing but (an aspect of) inheritance in a different guise.

Type matching is much more strict in StormC. This isespecially the case for the const qualifier used on functionparameters. An example:

typedef int (*ftype)(const int *);int f(int *);ftype p = f; // Error

For such errors you should either insert the necessary casts,or (and this is always preferable) write the appropriatedeclarations for your functions. After all the const qualifieris an important aid in assuring the correctness of yourprogram.

Rest-of-line comments as in C++ ("//") are accepted even inANSI-C mode, but nested C-style comments are not. In anycase you can enable the warning option that detects thesedangerous cases.

Accents in variable names are not accepted, nor is the dollarsign.

KeywordsThe use of non-standard keywords is generally best avoided- at least for programs that you may want to port to anotheroperating system or a completely different compilersomeday.

StormC User Manual 131

Page 132: StormC V3 Users Manual

6 COMPILER◆

StormC makes more use of the #pragma directives providedby ANSI-C for adapting software to the special requirementsof AmigaOS (eg. #pragma chip and #pragma fast).

For keywords that may not exist in other compiler systemsbut are not absolutely necessary, the use of special macros isrecommended:

#define INLINE __inline#define REG(x) register __##x#define CHIP __chip

These macros can then be easily modified to suit a differentcompiler environment.

Some optional keywords not recognized by StormC can alsobe defined as macros:

#define __asm#define __stdarg

Here’s a list of SAS/C keywords and how StormC interpretsthem:

__aligned is not supported. There is no simple way to replace thiskeyword, but fortunately it is rarely needed.

__chip This keyword forces a data item into the ChipMem hunk ofthe object file. Note that this keyword, like all othermemory-class specifiers and other qualifiers must precedethe type in the declaration:

__chip UWORD NormalImage[] = { 0x0000, .... }; // correctUWORD __chip NormalImage[] = { 0x0000, .... }; // error

The latter syntax is not accepted as it is not consistent withANSI-C syntax.

In StormC the use of "#pragma chip" and "#pragma fast"is preferred. Take notice however of the fact that "__chip"affects only a single declaration whereas "#pragma chip"remains in effect until a "#pragma fast" is found.

__far and __near are not supported. There is no easy way to replace thesekeywords, but they are rarely needed.

132 StormC - the professional choice

Page 133: StormC V3 Users Manual

Keywords◆

__interruptis not supported. At the moment all interrupt functions (ararely needed class of functions anyway) must be written inassembler.

__asm, __regargs, __stdargare not supported and not needed. If you wish to have

function arguments passed in registers, declare the functionwith the ANSI keyword "register" or modify theindividual parameter declarations with the "register"keyword or a precise register specification (eg. "register__a0"). Otherwise the arguments will be passed on the stack.

__savedsHas an effect similar to SAS/C’s "__saveds". This keywordhas no effect when using the large data model; in the smalldata model relative to a4 it saves a4 on the stack and loadsit with the symbol "__LinkerDB", in the small data modelrelative to a6 it does the same for a6.

Do not use "__saveds" lightly. It should be used exclusivelyfor functions that will be called from outside your program,eg. Dispatcher functions of BOOPSI classes.

In the current compiler version it is recommended to useonly the large data model when creating shared libraries.Remember that the small data model makes yet anotherregister unavailable to the optimizer leaving only a0 to a3 -this can quickly nullify the advantage of using the small datamodel if you’re not using a great deal of global variables.

__inlineLike the others, this keyword is accepted as a functionspecifier.

This means that their usage in a function definition mustmatch the prototype.

If an "__inline" function is to be called from severalmodules, its definition (not just its prototype) should beplaced in a header file.

__stackextis not supported. Stack checking or automatic stackextension is not available at this time.

StormC User Manual 133

Page 134: StormC V3 Users Manual

6 COMPILER◆

CLI VERSION OF THE COMPILER

There should actually be people who do not like theintegrated development environment. Therefore StormCcan be used as CLI version too. You will only need theprogram StormC from the drawer "StormC:StormSYS".

The concept The compiler creates object files from thesources, which will be bound to a program by StormLink.Without special option the compiler translates all indicatedsources and writes the object files.

The instructionStormSYS/StormC main.c text.c unter.c

compiles the three sources "main.c", "text.c" as well as"unter.c" and creates their object files. Subsequently youmust link the object files with the linker to get a finishedprogram.

If an error appears at the translation a suitable output with ashort portion of the source is output, along with an outputof the kind

File "filename.c", line 17:Error: Identifier "ths" not defined. Go on with <Return>, abort with <A>:

Now you can pass over the error with <Return> and continuethe translation or press <A> to abort the compilation.

StormC is capable of being resident, even if some Shellsannounce a sum error. This is harmless in each case, even ifStormC was made re-entrant on a somewhat unusualmethod: Using a semaphore a loaded copy of the programcares for that it does not run twice simultaneously.

OptionsAll compiler functions are steered through compiler options,which are indicated in the command line and beginrespectively with a minus character "-".

To bring a little order in this extensive jumble, the optionscan be divided using their respectively first letter intodifferent ranges:

134 StormC - the professional choice

Page 135: StormC V3 Users Manual

Options◆

- a Assembler Source Generation - b Debugs - d Symbol Definitions - e Error Messages - g Code Generation - h Pre-Compiled Headers - i Paths for Includes- j Paths for Libraries - l Linker Libraries- p Parser - s Copyrights- wWarnings and Main Memory Size

Options are always global: At a line of the form

StormSYS/StormC -x text1.c -y text2.c -z

"text1.c" and "text2.c" will be compiled equally with theoptions "x", "y" and "z". In other words: The sequence offile names and options is not relevant.

The sequence of the options mutually is not alike, ifcontradictory options appear in an instruction line. Forinstance you turn on with "-gO" the optimisation and with"-go" off. In cases like

StormSYS/StormC -go -gO etc.

the respectively last statement is valid.

Not only for the optimisation, but for almost each featurethere are two options: one to switch on and one to switchoff. At first glance that appears superfluously, because e.g.the optimisation is not activated by default and so an optionfor switching it off is not really necessary.

At the most switching possibilities the way was chosen, thatyou switch on with an uppercase letter and off with a lower-case letter like "-go" and "-gO".

The most important example is the option "-b" for thecreation of debugger files. The option switches are definedthrough appendices of a Zero. "-b0" means therefore "Nodebugger files".

In some cases abbreviations are introduced also, e.g. "-O" isidentically with "-gO". A two-letter-combination through

StormC User Manual 135

Page 136: StormC V3 Users Manual

6 COMPILER◆

an individual letter to abbreviate, is perhaps no particularlyimpressive saving. In this particular case "-O" has theadvantage to be compatible to other compilers.

Assembler source-a and -as Perhaps you would like to examine once the code created by

StormC, or you belong to the people, who want to optimisethe compiled program by hand. With the option "-a" youcan get the output of an assembler listing.

E.g.

StormSYS/StormC test.c -a

creates not only the object file "test.o" but also theassembler listing "test.s". The statement "-a" does notabort the translation process before the assembling, butcreates the source in addition to the remaining actions.

A pure assembler listing is rather tangled in most cases.Therefore there is the alternative "-as", through thestatements from the original sources will be inserted at therespectively corresponding positions as commentary in theassembler source.

To switch off these both options explicit you must use "-a0".

Pre-processor: Definition of symbols-d With the option "-d" you can define "from outside" a pre-

processor symbol. Thereby an argument corresponds to

-d NAME

a line

#define NAME

at the beginning of the source. A typical application is aninstruction like

StormSYS/StormC text.c -d NDEBUG

if the include file "<assert.h>" is used.

136 StormC - the professional choice

Page 137: StormC V3 Users Manual

Compiler mode◆

You can assign a value to the symbol by setting "=" directlybehind the identifier, e.g.

-d ANZAHL=4711

As value a token is allowed here only, that means at

-d N=17+4

would ignore that "+4".

Pre-processor: Include files-iThe path where StormC searches the include files is by

default set to "StormC:Include".

Through one or several "-i"-options you can change thispath: With the option

-i StormC:inc

the drawer "StormC:inc" will be looked for exclusively, andat

-i StormC:include -i StormC:include/amiga

the pre-processor searches successively in the both drawers.

Compiler modeANSI C or C++

-pc and -pp StormC can also be used as ANSI C compiler. If you do notwant to set "#pragma -" at the beginning of the source, youcan use the compiler option "-pc". C++ is the pre-set mode,which is the same as the option "-pp". Therefore "c" like "C"and "p" like "plus plus" - this is however completely easyto keep in mind.

Exception handling-px, -pX and -X Sometimes it is advantages, if you translate a "classic" C++

program, which does not use exception handling, in aparticular compiler mode. Then the key-words ("catch","throw" and "try") connected with the exceptiontreatment are recognised no more, and in the created codethere is no bookkeeping of the necessary destructor calls.That will make C++ programs faster and smaller. ANSI Cprograms will not be affected.

StormC User Manual 137

Page 138: StormC V3 Users Manual

6 COMPILER◆

As default the exception handling is switched off ("-px"). Ifyou would like to use the exception treatment you must turnit on first with "-pX". As abbreviation "-X" is allowed too.

Creation of Template functions-t and -T It is not always easy for the compiler to decide, which

Template functions it should create and which not. "-T"corresponds to the strategy "All Templates Create", at "-t" is pursued the other strategy to create what will be createdfaultlessly.

Code creationData model

-gd, -gd4, -gd6 and -gD The option "-gd" switches to "NearData (a4)" and "-gD"to "FarData" . Pre-set is "FarData". With the options "-gd4" and "-gd6" you can distinguish additionally, whetherthe data model should be created relatively to the address A4or to A6. The last one is very interesting at the creation ofShared Libraries.

Code model-gc and -gC The option "-gc" switches to "NearCode" model and "-gC"

to "FarCode" (default).

Optimisations-go, -gO and -O The additional optimisations are turned on with the option

"-go" and off with "-gO". Alternatively you can use for "-gO" also "-O0". By default they are off. "-O" can be used asabbreviation for "-gO". If the optimiser is turned on only,the compiler optimises in the supreme optimisation level.

Instead of switching the optimiser on and off there is thepossibility to switch to certain optimisation levels.

-O0 With the option "-O0" the optimiser will be switched off.This is the same as "-go".

-O1 This switches the optimiser to the first level where basicblocks are optimised. A basic block is a sequence ofintermediate code instructions, which contain no jumps.Successive blocks are summed up, which makes work easierfor later optimisation steps. Unused blocks are removedcompletely. The step is repeated until nothing more is to beimproved on this level. Also after higher optimisation steps

138 StormC - the professional choice

Page 139: StormC V3 Users Manual

Code creation◆

it is tried to sum up basic blocks and to remove unusedblocks.

-O2 Useless instructions like e.g. assignments at variables, whichare never used again will be removed.

-O3Variable and interim results are packed into processorregisters.

-O4Assignments at variables will be eliminated if the variable isnever used again. If a complete instruction can be eliminatedthat way the whole intermediate code will be optimisedagain, until no superfluous assignment is found any more.

Example:

In this complete useless function

void f( int i){int j = i+1;int k = 2*j;}

only the second instruction will be recognised as useless atlower optimisation levels. From level 4 on the code isperused subsequently once more and then the firstinstruction will be eliminated too.

-O5 At the M680x0 code generation MOVE commands todestination register, which are used subsequently only oncebefore they receive a new value, are pushed together ifpossible. So

move.l 8(a0),d2 add.l d2,_xyz

becomes thereby

add.l 8(a0),_xyz

-O6At the interpretation of expressions the interim results of allkind will be laid to auxiliary variables at code generation andpacked to processor registers later. At lower level theseauxiliary variables will be recycled if possible to keep theirnumber low. The expression "a*b+c" would create thefollowing intermediate code instruction:

StormC User Manual 139

Page 140: StormC V3 Users Manual

6 COMPILER◆

h1 = a*bh1 = h1+c

From level 6 on the auxiliary variables are never used again.The generated intermediate code would look like:

h1 = a*bh2 = h1+c

In later optimisation step there will be a check whether itmakes sense to pack "h1" and "h2" in the same registers.That costs time and RAM because of the increasing numberof internal auxiliary variables, but it allows to make a gooddistribution of the registers.

Code for special processor-g00- -g60, -g80 and -g81

Also there are always fewer Amiga-User which use a normal68000 processor StormC normally generates code for thisprocessor. It is compatible to all further processors of thisfamily. Indeed Motorola implemented some new commandsto newer processors beginning with the 68020. They willaccelerate programs partially, i.e. at multiplication and atarray access. The following options switch to the codegeneration for certain processors:

-g00 68000 (default)-g10 68010-g20 68020-g30 68030-g40 68040-g60 68060

In the current version of StormC the options "-g20" and "-g30" are identical. Indeed the options "-g40" and "-g60"differ drastically from the others. Since some FPU functionsare not implemented, they must be emulated. At codegeneration for 68040/060 processors particular libraries areused to create no FPU commands like it is done in othercompiler systems.

The use of a Floating Point Unit (FPU) will speed upprograms that use many floating point operations ("float"and "double"). With the following options StormC createscode for FPUs:

-g80 without FPU (Default)-g81 68881

140 StormC - the professional choice

Page 141: StormC V3 Users Manual

Debugger◆

-g82 68882 (identically with -g81)

Code for linker libraries-gl, -gL and -L If desired, StormC can put each function and each global

variable in separate hunks. As the linker does not takes non-referenced hunks into the executable program file, thismode suits particularly for linkable libraries. With "-gL" or"-L" this option is turned on. "-gl" switches to normalmode.

DebuggerRunShell

-b, and -b0 "-b" creates the necessary debugger files (".debug" and".link"). "-b0" switches to original mode.

Symbolic debugger-bs and -bs0The option "-bs" creates symbol tables hunks for symbolic

debuggers.

Copyrights -sThe option "-s" outputs the following text at the call of the

compiler:

Programname versionnumber (creationdate), copyright, author

Example:

StormC 1.1 (07th05.96), Copyright (c) 1996 HAAGE &PARTNER computers Ltd.

Warnings and errorsFormat of the error output

-e, -el and -eiStormC can output error messages in three different kinds:interactive, in short or long format. The pre-set is"interactive" error output, for which also the option "-ei"can be used. Thereby for each error message a short sourcesection (approx. 5 lines), the source position and a prompt("Go on with <return>, abort with <A>:") is shown.The exact error position is emphasised in the source sectioncolourfully. After pressing <Return> or alternatively <Space>or <C> the translation is continued. At input of <A> oralternatively <ESC> or <Ctrl>+<C> the translation is aborted.

StormC User Manual 141

Page 142: StormC V3 Users Manual

6 COMPILER◆

The compiler option "-e" switches on short output. Hereonly two lines, the source position and a short message areoutputted at each error and each warning. After ten errorsthe translation process is aborted anyway. You can chooseanother value for that number if you append it just after theoption i.e. "-e20".

The long format is a mixture from interactive mode and theshort one. Thereby sources and error message are outputtedlike at "-ei" but it does not wait for an input. After amaximum of ten errors the compiler aborts the action. Forthis form of the error output you choose the option "-el".As on the option "-e" you can choose the abortion level byadding a number. E.g. "-el5" would be a meaningfulsetting, since ten messages would not fit into a normal Shellwindow.

Colours and styles-eb, -eB and -ec The however somewhat boring text output can be made

more clearly. There is the possibility to show the real errormessages in bold with the switch "-eB". "-eb" switches backto basic attitude. The option "-ecN" brings colour in thegame, at least if you use a numeral for "N". The screen colournumber "N" is used to differ between the source section ofother outputs. "-ec1" corresponds to the standard textcolour and "-ec0" is (theoretically) the background colour.Since you could not read the text any more in the more lastcase, so "-ec0" outputs the source in colour 2, but the errorposition in an other colour than "-ec2".

Error file-ef For the linking of StormC in foreign environments it can be

useful, to reroute all error messages in a file. That is done bya statement like "-ef <name>". Thereby all error messagesand source positions are written in the indicated file. Thedifference to a simple output routine is that "-ef" works inaddition to the normal screen output and secondly it doesnot appear as a status messages in the file.

142 StormC - the professional choice

Page 143: StormC V3 Users Manual

Warnings and errors◆

Optional warnings-w You turn on a optional warning by pacing their character as

BIG ones behind that "-w", while a small letter switches itoff.

These are the warnings and their characters:

A (Assignment): The operator "=" appears in a condition -perhaps a the will-known "=="-novice-error? You caninhibit such a warning by an additional brackets, i.e. "if((a=b))" instead of "if (a=b)".

C (Conversion): Uncertain type conversion without cast,i.e. double -> int.

E (Empty statement): Instruction has no code, i.e. "36;"

F (Function prototypes): Function called without aprototype (only meaningful in C as in C++ it is an error).

N (Nested comments): A "/*" emerges in a comment.

O (Old-Style): Complaining about parameter lists in the old"K&R"-style (only meaningful in C as in C++ this is anerror).

P (Pragma): Unknown "#pragma".

R (Return): Function with return value has none "return"-statement.

T (Temporary): Temporary object was introduced, toinitialise a non-const-reference, which is an error in C++since standard 2.0.

V (variable): Local variable is used never, or used, but neverinitialised.

M (Macro): An argument for a pre-processor macros extendsover more than 8 lines or 200 tokens. It is obvious thatthere is a closing bracket missing.

By default "-wEPRT" is activated. I.e. to switch warnings atmissing prototypes on and off such at unknown "#pragma",you can simply use the option "-wFp" or alternatively bothoptions "-wF -wp".

StormC User Manual 143

Page 144: StormC V3 Users Manual

6 COMPILER◆

Please note, that "-w+v" does NOT mean that the

warning "v" is turned on in addition to the current, but that completely all warnings are switched on and subsequently "v" off again.

To turn on all warnings - by the way a sign for goodprogramming style - is some typing work. To make it a littleeasier there is an abbreviation: a "+" directly behind that "-w" turns on all warnings.

You can also switch off all warnings with "-w-", but I wouldnot advice this to you. A "clean" program should output anywarnings, at most "a"-warning are possibly as printout ofyour personal programming style. If you take warningsactually so seriously, the following section will be veryinteresting for you.

Treat warnings like errors-ew and -eW With the option "-ew" warnings are treated like error

messages. "-eW" switches back to normal mode.

Core memories-w Of course StormC allocates the memory for the most internal

processes automatically and dynamically, but at codegeneration there must be a coherent memory area. This sizeis 80 KByte by default. If there is the message "Workspaceoverflow!" you should increase the amount with the option"-w" cautiously, i.e. "-w150" for 150 Kbytes.

Pre-compiled header files-H, -h and -h0 StormC can pre-compile parts of a program. That means that

the compiler can store all its internal data like declarationsand definitions, at a user selectable position. At the next runof the compiler this file can be loaded very quickly and so itsaves much time.

This feature is for speeding up program development,especially when many header files are used i.e. the AmigaOS-Includes. To tell the compiler where the headers ends andyour program begins, you must mark this position with thecommand "#pragma header".

It is best to write the "#include"‘s of the header files you didnot do by your own or which you will not change any moreat the first place in the source of all units. Then the line"#pragma header" follows. Next parts are the includeinstructions for your own header files and the rest of yourprogram.

144 StormC - the professional choice

Page 145: StormC V3 Users Manual

Summary◆

Without special option or with the explicit switch "-h0","#pragma header" has no effect. If you indicate an option"-H <name>", the compiler stops shortly as soon as it reachesthe pragma and writes all definitions and declarations intothe file "<name>". To accelerate the program compilationnow you must choose the option "-h <name>". Then thecompiler reads the pre-compiled headers from the indicatedfile, searches the source for "#pragma header" andcontinues this work form there.

Since everything which stands before "#pragma header" iscompletely ignored, it has to stand consequently in the mainsource file and not in an include file.

Please keep in mind that the compiler does not check,whether the content of the pre-compiled header files stillcorresponds with the original source. Therefore Irecommend to compile such header files only which will notbe changed any more.

SummaryNow a short, alphabetically organised summary of alloptions follows:

-a Creates an assembler source for each translatedtext file.

-as C source is inserted as commentary intoassembler source.

-a0 No assembler output (default)-b Create small debug information file. -bf Create large debug information file.-b0 Without debug information file (default).-bs Create "symbol hunk" for symbolic debugger.-bs0 No symbol hunk (default)-c Compile sources and creates the corresponding

".o" files.-d NAME Defines a pre-processor symbol. Optionally a

"=" and the desired value (only a token) can beset directly behind the name. Otherwise thesymbol is defined as "empty".

-eB Error messages written in bold.-eb Error messages written normally (default)-ecN Output source in colour number "N" at error

messages.-ef xxx Write error messages to file "xxx".

StormC User Manual 145

Page 146: StormC V3 Users Manual

6 COMPILER◆

-ei Ask the user whether he wants to abort at eacherror message during compilation (default).

-e[N] Output error messages without user inter–action. After "N" errors compilation is aborted(default is 10).

-el[N] Like "-e", but with source output in addition.-ew Treat warnings like errors.-eW Output warnings, but ignore them (default).-gd Data model "Near Data (a4)".-gd4 Same as "-gd".-gd6 Data model "Near Data (a6)".-gD Data model "Far Data" (default). -gc Code model "Near Code". -gC Code model "Far Code" (default).-gl All functions in one section (default).-gL Library mode: Create an own section for every

functions and global variables.-go No optimisation (default).-gO With optimisations.-g00 Generate code for 68000 (default).-g20 Generate code for 68020.-g30 Generate code for 68030.-g40 Generate code for 68040. -g60 Generate code for 68060.-g80 Do not generate code for FPU use (default).-g81 Generate code for 68881-FPU.-g82 Generate code for 68882-FPU. -H xxx Store pre-compiled header files. -h xxx Load pre-compiled header files.-h0 Do not use pre-compiled headers (default). -i xxx Set path(s) StormC should use to look for

includes. It is possible to use multiple "-i" foradding more paths. The default is "StormC:include".

-L Abbreviation for "-gL" -o xxx Sets an other name for the object file.-O Abbreviation for "-gO"-O0 Alternative for "-go" -O1 Turns on the optimiser level 1.-O2 Turns on the optimiser level 2.-O3 Turns on the optimiser level 3.-O4 Turns on the optimiser level 4. -O5 Turns on the optimiser level 5. -O6 Turns on the optimiser level 6. -pc Switches to ANSI C mode.-pp Switches to C++ mode (default).-px No exception handling.

146 StormC - the professional choice

Page 147: StormC V3 Users Manual

Summary◆

-pX With exception handling.-s Outputs the copyright message and the version

number of StormC. -t Create faultless template functions only.-T Create all required template functions. -w xxx Output warnings. An arbitrary sequence of

characters can follow. Big ones will turn onwarnings, small ones will turn them off.

There are the following warnings:

A (Assignment): Operators "=" appears incondition. Perhaps the will-known "=="-noviceerror?

C (Conversion): Uncertain type conversionwithout cast, i.e. double -> int.

E (Empty statement): Instruction has no code, i.e."44;"

F (Function prototypes): Function called withouta prototype (only acceptable in C, because inC++ it is an error)

N (Nested comments): "/*" in commentary. M (Macro): An argument for a pre-processor

macros extends over more than 8 lines or 200tokens. It is obvious that there is a missingclosing bracket.

O (Old-Style): parameter lists in the old "K&R"style (only acceptable in C, because in C++ it isan error).

P (Pragma): Unknown "#pragma".R (Return): Function with return value has no

"return".T (Temporary): Temporary object was introduced

to initialise a non-"const" reference (this is anerror since that 2.0 standard).

V (variable): Local variable is never used and/orused, but never initialised.

By default "-wEPRT" is activated.

-wN Sets the interim compiler workspace on "N"Kbytes. Default is 80 Kbytes, which should beenough for most cases.

-w+ Output all warnings. -w Output no warnings. -X Abbreviation for "-pX".

StormC User Manual 147

Page 148: StormC V3 Users Manual

6 COMPILER◆

148 StormC - the professional choice

Page 149: StormC V3 Users Manual

Debugger7 ◆

7 The Debugger

fter the first successful compilation of a program the test phase starts. Ofcourse you could simply run the program from a CLI (or a Shell), yet thiscan cause some typical Amiga problems:

1. If the program makes serious errors, which is always possible in C or C++, thecomputer may crash, because the CPU has so called exceptions, i.e. special soft- orhardware states. These are treated only very generally by the OS, and often don’tallow you to work on in a reasonable manner without rebooting the system.

2. Rebooting the Amiga is the only solution in most cases when the program is runninginto and endless-loop.

3. After an exception or when the program is stopped by “exit()“ or “abort()“ mostof the system resource are still reserved. While still reserved memory is onlyannoying, open files or windows may hinder the further work very much or even leadto crash of the OS.

4. The problems mentioned here cannot be traced back to their origin in the sourcecode.

GENERAL INFORMATION ON RUNSHELL .................................. 151

The StormC Maxim ..................................................................................... 151

A Resource-Tracking Example ................................................................ 152

Freeze the program temporarily .......................................................... 153

Halting the program .................................................................................. 154

Changing the task priority ...................................................................... 154

Sending signals ............................................................................................ 154

USING THE DEBUGGER ................................................................................... 157

The Variable Window ................................................................................ 159

Temporary Casts .......................................................................................... 161

Changing Values .......................................................................................... 161

Sorting of Variables ................................................................................... 161

A

StormC User Manual 149

Page 150: StormC V3 Users Manual

7 THE DEBUGGER◆

THE PROFILER ...................................................................................................164

Profiler technical information ...............................................................167

REFERENCE ..........................................................................................................169

Control Window ...........................................................................................169Status line .........................................................................................................169“Program Stops At Breakpoint“: .......................................................................169“Continue Program“: ........................................................................................169“Program waits for ...“: ....................................................................................169Debugger icons .................................................................................................169Go to next breakpoint .......................................................................................170Step in (single step) ...........................................................................................170Step over (single step, but execute function calls without stopping) .................171Go to the end of the function. ...........................................................................171Show Current Program Position .......................................................................171Pause ................................................................................................................172Kill ....................................................................................................................172Priority gadgets ................................................................................................172Signal group .....................................................................................................172Protocol gadgets ...............................................................................................172Window close gadget .......................................................................................173

Current variable window ..........................................................................174

The module window ...................................................................................177

The function window .................................................................................178

The history window ....................................................................................178

The breakpoint window ...........................................................................179

The address requester ...............................................................................180

The hex editor ...............................................................................................181Choosing the display ........................................................................................181The address string gadget ................................................................................181The address column ..........................................................................................181The hexadecimal column ..................................................................................181The ASCII column ..............................................................................................181Keyboard control ..............................................................................................182The scrollbar in the hex editor ..........................................................................182

150 StormC - the professional choice

Page 151: StormC V3 Users Manual

The StormC Maxim◆

GENERAL INFORMATIONON RUNSHELLIt is for the four reasons of the introduction to this chapterStormC has a "RunShell". It will launch the program similarto a start from the CLI, yet it caters for a whole range of waysto control and direct the program.

A special feature is "Resource-Tracking", which solvesproblem 3, for example. After the program is interrupted orfinished, all resources that have been allocated but not freedwill be shown. The resources are then freed by the RunShell.Next the position in the source code where the resource wasallocated can easily be jumped to.

Connected to this RunShell is the Source Level Debugger. Itallows you to execute programs step by step, localise errors,or inspect variables. But also directly control the program,and always find the origin of problems (in the worst case acrash) in the source code.

Additionally it is possible to halt the program (for examplein endless loops), without having to compile the program ina special way.

The StormC MaximThe program is in the test phase is equal to the final product.To be able to use the source level debugger you need tocompile with the corresponding option, yet this doesn’tinfluence the generated program. This prevents the problemother systems from time to time have: bugs that show upwhen running a program under normal conditions can’t bereproduced using the debugger.

A further special feature is the ability to switch from normalexecution to the debugger, and to return from the debuggerto normal execution (if the program was compiled using the"debug" option).

StormC User Manual 151

Page 152: StormC V3 Users Manual

7 THE DEBUGGER◆

A Resource-Tracking ExampleOpen the project "IllResource.¶" in the "StormC:Examples/IllResource" drawer. This program allocatessome resources without freeing them.

Start the program using for example the function key F9.Subsequently the program will then be compiled if necessaryand then run.

Other ways of launching your program are: selecting thebutton in the toolbar with the walking man on it, selectingthe menu item "Start" from the "Compile" menu, doubleclicking the entry for the program in the project window, ordirectly after compiling by hitting the "Start" button in theerror report window.

152 StormC - the professional choice

Page 153: StormC V3 Users Manual

Freeze the program temporarily◆

After compiling the Runshell control window will beopened. This is your "control board" for the program.

The status-line shows help texts for elements of the controlwindow and also the status of your program, when you’renot above any control gadgets.

The "IllResource" program now shows that it’s waiting(the "Wait()" function of "exec.library"), and also showsthe mask of the signal flags that it is waiting for. At themoment this reads "0x00001000", which corresponds to aCtrl-C.

De icons in the "Debugger" group aren’t needed for themoment, first we want the program to execute normally.The debugger can be activated with the checkmark on thegroup frame, the icons in this group stand for "Go", "Stepin" (single step), "Step over" (single step, but executefunction calls without stopping), "Go to end of function"and "Show last found program position". Thesefunctions will be explained later in the debuggerintroduction.

Freeze the program temporarilyThe "Pause" button allows you to freeze the program at anytime, e.g. when you wish to inspect the contents of awindow, that would have been overwritten quicklyotherwise. This button toggles, first the button is"lowered", and stays that way. The program will be frozenuntil you "raise" the button again by selecting it once more.

StormC User Manual 153

Page 154: StormC V3 Users Manual

7 THE DEBUGGER◆

The program will continue to execute. The menu item"Pause" in the "Debugger" menu also freezes the program.

Halting the programNext to it is the "Kill" button. This martial action allows youto end program execution at any time. The menu item "Kill"in the "Debugger" menu has the same result.

Especially by setting too high a priority for your

program you can block the system. Please be careful when changing this setting.

Changing the task priorityThe "Priority" group shows the priority of the program andallows you to change it. Even though the priority can bechanged throughout the whole range of -128 to 127, itshould be restricted to the range of -20 to 20, otherwisetroubles with other programs or even an unusable systemcan result.

The value set at program start (normally "1") is really asensible one, because it is one step minor than the priorityof the debugger, so working with the debugger is alwaysfluently.

Sending signalsThe "Signals" group contains four buttons, to send the fourinterruption signals of AmigaDOS:

Ctrl-C, Ctrl-D, Ctrl-E, Ctrl-F.

You can very easily control a program while testing by usingcorresponding "Wait()" statements. Much like the program"IllResource" that currently waits for a Ctrl-C before itallocates the resources.

Now select the "Ctrl-C" button in the "Signals" group.

154 StormC - the professional choice

Page 155: StormC V3 Users Manual

Sending signals◆

The program has now allocated some resources, but it didn’tfree them again, The program has finished.

Even though Resource-Tracking always

works and the Runshell always frees the resources, the source code position can only be shown if the program was compiled with debugging information.

The protocol list shows information about resources thatwere allocated and not freed. This involves memoryallocations, libraries, and a file.

Double-click a line in the protocol list, and the position inthe source code where the resource was allocated will beshown. If the source code wasn’t available in an editor tobegin with, a new window will be opened and the sourcecode will be read.

StormC User Manual 155

Page 156: StormC V3 Users Manual

7 THE DEBUGGER◆

In a real program you could now start on writing theappropriate code to free the resources. Where this should bedone of course depends on your program.

To be able to show the position in the source code whereresources are allocated incorrectly, one condition must befulfilled:

The corresponding OS function must be called directly inthe source code. This rules out calls from link-libraries,i.e. OS functions should not be called via "amiga.lib"and the stub-functions contained therein, but insteadalways use the correct "#pragma amicall" and"#pragma tagcall" calls.

Now free the resources using the menu item "FreeResources" from the "Debugger" menu, or directly closethe control window, which will automatically close theresources.

156 StormC - the professional choice

Page 157: StormC V3 Users Manual

Sending signals◆

USING THE DEBUGGER

Load the project "StormC:Examples/Debugger Tutorial/DebuggerTutorial.¶". The program consists of manymodules with one header file, just enough to also show somenon trivial debugging situations.

Start the program normally and get familiar with it. First amenu with three items will appear:

• enter an address, • show all stored addresses and • end of program.

If you wish to enter a new address, enter 1 (don’t forget<Return>). Then enter a person’s last name, first name, streetand place of residence. Repeat this two or three times andhave a look at the result by choosing menu item 2. Then endthe program.

Because normally you only debug your own programs, youshould now have a look at the source to get familiar with thefunction names.

The main program is in "main.c". It shows the main menuand evaluates the menu input. Depending on the inputfunctions from "address.c" will be called.

StormC User Manual 157

Page 158: StormC V3 Users Manual

7 THE DEBUGGER◆

First up in the "address.c" module are some staticfunctions for use by the other functions. Then all the addresshandling functions follow.

The header file "address.h" contains the "structAddress" data structure and the prototypes of all functionsthat do something with addresses, particularly input andoutput. These functions are implemented in the"address.c" module and are called by the "main.c"module.

When so far everything is clear, start the program again, onlynow in the debugger, i.e. with F10 or the corresponding iconin the toolbar.

Other ways to debug a program are: the menu item "Debug"in the "Compile" menu, double clicking the program namein the project window while simultaneously holding the<Alt> key, or directly after compiling in the error window byselecting the "Debug" button.

Again the control window is opened first, only now withactivated debugger controls. The program will automaticallyexecute to the first position in the program for which sourcecode is available. If you haven’t already loaded the "main.c"source, it will happen now. The editor window now looks abit different: a column of breakpoint buttons is located tothe left of the text.

A breakpoint button is there for every position in

the source where the program can be stopped, breakpoints are the positions in the program where execution will stop, when it was started with "Go" (and runs at full CPU speed).

In this column you can set or clear a breakpoint with themouse. This column also shows how far a single step takesyou, since often a step in C takes you more than one line

158 StormC - the professional choice

Page 159: StormC V3 Users Manual

The Variable Window◆

ahead (for example skipping comments, declarations, longexpressions etc.).

The current program position is always in the editor shownusing a white bar that marks the whole line horizontally.

The Variable WindowSubsequently the window with the variables is opened.. Thisalways shows all variables that are available to the programat this time.

At the first line of the window a short help text is shown,which tells you the meaning of the different buttons of thiswindow.

Below this line is the button line. On the left side there are4 buttons to select one of the 4 variable pages.

StormC User Manual 159

Page 160: StormC V3 Users Manual

7 THE DEBUGGER◆

The 1st page shows all parameters and local variables of thecurrent function and the global variables of the module thatcontains this function.

The 2nd page contains all global variable of all modules.

The 3rd page shows the variables that should be supervised.This can be local variables of functions or even parts of astructure (members).

The 4th page contains the cpu register values.

Choose the first variable ("address") out of the list of thecurrent variables, by selecting its name. Next you can alsoreach other elements of the window.

Next to the buttons for paging you will find these for actionson the selected variables.

By selecting the 1st button the source code position wherethe variable is defined 3will be shown by positioning thecursor there.

The 2nd button is interesting for C++ programmers. It showsa list of all member functions of the type of this variable. Thislist will be empty, because in this example there are nomember functions.

The 3rd button inspects a variable. The variable will belooked for very exactly e.g. every field of a structure is shownindividually.

The 4th button returns from the inspection and the value ofthe variable list will be the same as before the inspection.

The 5th button opens the hex-editor and puts the cursor atthe address of the variable.

The 6th button adds the variable to the watched variableswindow. This allows you to build a list of variables that youalways want to see, even if the program is not executing thecorresponding module or function.

The 7th button is only available on the page of the watchedvariables. It deletes a variable out off the list of watchedvariables.

160 StormC - the professional choice

Page 161: StormC V3 Users Manual

Temporary Casts◆

Temporary CastsThe string gadget "Cast" allows for easy casting of the typeof a variable. You may enter a type here that is definedsomewhere in the module. Pay attention to write the typelike it is shown in the variable list. If the type is found thevalue of the variable will be interpreted according to the newtype. E.g. it might be sensible to make an "ULONG" a "LONG"to get the signed value. The most often used application isto change the target type of a pointer, e.g. to make "Message*" an "IntuiMessage *". At next inspection of the variablethe new type will be used.

The old type will always we shown in the variable list. Thenew one is only in the string gadget "Cast". When you wantto return to the old type you must only delete the contentsof the string gadget and press <Enter>.

If you entered a wrong type the screen will flash and theformer contents will be restored.

Changing ValuesWhen you have selected a number variable (here forexample the third variable "illegal"), you can directlymodify the value of the variable in the "Value" stringgadget, without having to bother with the hex editor.

When you selected a variable which type is a pointer toUBYTE or BYTE (also called a "string") you can change the textat string gadget "value". Pay attention not to enter morecharacters than is reserved for that string.

Sorting of VariablesFirst the list of variables is unsorted. Now you can select thesorting method with the cycle gadget "Sort". Thealphabetical sorting will use the names of the variables forsorting, so you can find a certain one quicker in a big list."Last Changed" will put the variable on the top that waschanged last. This sorting will be updated after everyprogram step. The debugger recognises every change, evenchanges of single struct fields or variables, which arechanged through pointers.

The sorting method can be selected separately for every ofthe 3 variable pages.

StormC User Manual 161

Page 162: StormC V3 Users Manual

7 THE DEBUGGER◆

Now execute some statements of the program by selectingthe middle icon in the "Debugger" group. In the editorwindow you’ll see how the program executes one "printf"function after the other, with the output appearing at thesame time in the console window. The status line in thecontrol window shows "Breakpoint reached" after eachstep. When you take a step that takes longer, for examplewhen reading input from the console, you can also read the"Program continues" message.

At some point you’ll reach the "gets(s)" statement on line25. When you step through this function you will of coursehave to type the corresponding input in the consolewindow.

Please enter <1> and then <Return>. In the switch-statementyou’ll now enter the first branch. On line 29 you’ll find thefunction call for the function "readAddressmask()". Thisfunction resides in the "address.c" module. Don’t selectthe step over button, but instead choose the second buttonfrom the left, to execute the program in single steps. Thisway you’ll enter the function "readAddressmask()".

The source for the "address.c" module will now be loadedand the source code position will be shown. Now go step bystep through the function. Depending on whether you usethe second or third of the debugger icons in the controlwindow, other function calls will either be stepped throughor executed without stopping.

When needed, enter name, first name, street and place ofresidence in the console window.

Before ending the function, you can try the 4th button fromthe left in the "debugger" group. This one will execute theprogram without stopping until the end of the function isreached and you will return to the main program again.

Now you should be on line 30, and the variable "address"should have a sensible value. You can check this now: selectthe variable in the current variables window, and select thebutton "I" to examine it.

The elements of the "struct Address" will replace thevariable list.

162 StormC - the professional choice

Page 163: StormC V3 Users Manual

Sorting of Variables◆

You can change the entered strings even now. Select e.g. thefield "name" and change the contents in the string gadget of"value". In this case you should only enter a string notlonger than the old one, because the program has onlyreserved this space in the dynamic memory by "malloc()".

Continue bug hunting and try a couple more things, forexample watching variables and structure fields. When youfeel comfortable with the debugger, end the program, eithercorrectly or with "Kill".

StormC User Manual 163

Page 164: StormC V3 Users Manual

7 THE DEBUGGER◆

THE PROFILER

A profiler is an indispensable tool when optimizing aprogram. Compiler optimizations can only improveprogram performance by so much, whereas a profiler canprovide the necessary information for identifying the mosttime-intensive functions in a program. These functions canthen be rewritten to use better algorithms if possible, or atleast sped up by carefully optimizing the source code byhand.

The StormC profiler is especially powerful; it allows precisetiming and provides many valuable statistics about theprogram.

As always, we have stuck with the our maxim in that nospecial version of the program needs to be generated forusing the profiler. Having the normal debug informationgenerated will suffice. This - like the ability to start theprofiler while debugging - is probably unique for compilerson the Amiga.

If you wish to use the profiler, make sure your project iscompiled with the Debug option set to either “smalldebug files“ or “fat debug files“. Select the “Useprofiler“ option in the Start Program window. Theprogram can then be started as normal. Simultaneousdebugging is possible, but may lead to minor deviations inthe profiler’s timing measurements.

After starting the program, the profiler window can beopened.

The upper-left corner updates the profiler display, changingall indicated percentage and timing values to reflect thelatest results.

164 StormC - the professional choice

Page 165: StormC V3 Users Manual

Sorting of Variables◆

The help line shows the cumulated CPU time. This value isthe amount of real CPU time used, ie. it does not includetime that the program spends waiting (for signals, messages,or I/O) or time used by other programs that are running inthe background.

The list below shows the functions including the followinginformation:

1. Function name.Member functions of a class are displayed using the “scopeoperator“ syntax (class name and member name separatedby two colons).

2. Relative running time.This counts only the time that the program spends in thefunction itself, or in OS functions called directly from it. Anytime this function spends calling other functions in theprogram is omitted.

This value provides the best hint as to which function usesup the most time. The sum of all values in this column willbe 99 - 100% (the missing percent is lost in startup code andminute inaccuracies).

3. Relative recursive running time.

Here all subroutine calls from a function are included in itsrunning time. For this reason the main() function willnormally show a value of 99%.

4. Absolute running time. 5. Longest running time. 6. Shortest running time.

These three lines give you a quick overview over theinvocations of each function. Just how a function can bemade faster often depends on whether the invocationsgenerally take roughly the same amount of time to finish(small difference between longest and shortest runningtime), or some invocations take noticeably longer tocomplete than the others (great difference). In the latter caseit may be profitable to optimize those special cases.

7. Number of invocations.Sometimes a function makes up a large chunk of theprogram’s running time only because it is called very often,but each individual invocation takes up very little time.Optimizing such a function is usually a tough nut to crack.However it may be very beneficial in such a case to declarethe function inline (“__inline“ in C, “inline“ in C++).

StormC User Manual 165

Page 166: StormC V3 Users Manual

7 THE DEBUGGER◆

Above this list are several controls related to the profilerdisplay:

The uppermost line is the help line which shows briefdescriptions of the controls.

Directly below that, to the left, you see three buttons. Thefirst of these updates the list of functions.

The second button lets you save the profiler display as anASCII text file. A requester will appear to let you select a filename.

The third button dumps the information to the printer(using the “PRT:“ device).

On the right-hand side of this line are the sorting controlsfor the function list. The first entry “Relative“ sorts the listby the values in the second column, “Recursive“ sorts bythe third column, and “Alphabetic“ sortsalphanumerically by the function name shown in the firstcolumn. And finally “Calls“ sorts the list by the contents ofthe last column.

The line below this holds a text entry field for a DOS patternstring. Only those functions are shown whose names matchthe pattern; this can help reduce excessively long functionlists to a manageable size. This can be used for instance toonly show member functions of a particular class by enteringthe class name followed by “#?“.

To the right of this sits a numeric entry field where you mayenter the minimum percentage of running time that afunction must take up in order to be shown in the list.Functions that make up less than 5 or 10% are often difficultto optimize and even doubling the speed of such a functionis hardly worthwhile as the program would not becomenoticeably faster (a mere 2.5 or 5% in this case).

These optional restrictions aside, only those functions areever shown that are invoked at least once while the programis running.

Double-clicking on a function entry will take you directly toits location in the source text.

166 StormC - the professional choice

Page 167: StormC V3 Users Manual

Profiler technical information◆

The profiler display is also opened and updatedautomatically when the program terminates. The controlwindow will also remain open. Closing the control windowwill also cause the profiler display to close and the list isforgotten. Should you want to have access to thisinformation afterwards, make sure you have saved it to fileor printed a hardcopy before closing the window.

Profiler technical informationThe LINE-$A instructions $A123 and $A124 are used to markfunction calls.

These machine language instructions are unused on allmembers of the Motorola 68K processor family and triggeran exception. This exception is used to update the timingand call statistics.

The use of exceptions has the relative drawback of reducingthe effective CPU speed, ie. the program will take longer toexecute when the profiler is running than it does when theprofiler is not activated. The difference will be particularlynoticeable if the program invokes a lot of short functions.However the profiler will still be faster and more accuratethan most existing profilers for the Amiga OS. The techniquealso buys the advantage of not having to recompile yourcode especially for profiling.

Handling of recursion is limited: The longest and shortestexecution times will usually be unreliable, the totalexecution time (and therefore the relative values also) maybe incorrect. A simple case of recursion (where f() calls f())shows the correct relative values, but in the case of nestedrecursion (where eg. f() calls g() which calls f()) cumulatesall times onto one of the two functions.

Function calls leading out of the recursion will still be showncorrectly.

The effect on long jumps is not predictable, but in most casesthis should only lead to minor distortions of the statistics forthe called function.

Theoretically speaking, not all functions can be measured:Only functions whose machine code starts with a link ormovem instruction are available to the profiler. One of theseinstructions will however be necessary in almost all cases,

StormC User Manual 167

Page 168: StormC V3 Users Manual

7 THE DEBUGGER◆

even at the highest optimization levels. And fortunately anyfunctions that do not need these instructions will be so small(no variables on the stack, only the registers d0, d1, a0, anda1 are altered) that optimizing them any further would benear-impossible anyway.

Inline functions generally cannot be measured.

168 StormC - the professional choice

Page 169: StormC V3 Users Manual

Control Window◆

REFERENCE

Control WindowThe control window is used to direct the program and forresource-tracking. It is opened automatically at the start of aprogram.

Status lineShow short help texts about control window gadgets in textcolour (black), and program status messages as importanttext (white).

“Program Stops At Breakpoint“:The program reached a breakpoint and stops. This canalso be a breakpoint set by the debugger to make itpossible to interrupt between C and C++ statements thatoften exists of more than one machine code command.

“Continue Program“:The program is running.

“Program waits for ...“:The program waits at an exec function "wait()" forsignals. The signal mask is shown.

Debugger iconsThe group with debugger icons contains a checkmark in theborder to switch the debugger on and off. When thedebugger is on the buttons that control execution areavailable.

StormC User Manual 169

Page 170: StormC V3 Users Manual

7 THE DEBUGGER◆

When the program is started just „normal“ the debugger canbe switched on at every time. Then the debug information isloaded. The program must be stopped by a suitablebreakpoint. A module must be selected out of f the modulewindow to set the breakpoint in the corresponding sourcecode or a function is selected to set the breakpoint there.

Go to next breakpointIf you didn’t put a breakpoint in your program, the programwill be executed normally.

The program will execute at maximum CPU speed, until thenext breakpoint is found (this needs to be set by the user inthe editor). Because the debugger and the editor run in fullmultitasking together with the program that is beingdebugged, breakpoints can be set at any time.

The menu item "Go" in the debugger menu has the sameeffect.

Step in (single step)This step will always go to the next breakpoint button visiblein the source code. When present, function calls will beentered and breakpoint buttons will be used here similarly aswell.

Functions without available source code will also beexecuted in single step mode, to allow stopping in functioncalls to code that has source code available again. Suchjumps back can also happen in link libraries using functionpointers or virtual function members in C++ classes. Theexecution speed of library functions is therefore low.

Functions of shared libraries will always be executed at fullCPU speed. At recall of the program from such a library it cannot be stopped. If the behaviour of a hook function shouldbe tested a breakpoint must be set in the hook functionbefore the call of the library function that calls the hookfunction.

Under certain circumstances it is critical to single step"Forbid()"/"Permit()" sections. The protection is brokenafter every stop (the program sends a message to thedebugger and waits for an answer) and other tasks can runagain. When at this time one of the global system lists is notcorrect the system might crash. When the "Forbid()"/

170 StormC - the professional choice

Page 171: StormC V3 Users Manual

Control Window◆

"Permit()" section is only used to copy the contents of aglobal data structure (e.g. the list of all waiting tasks of thesystem) it is probable that the result is incorrect.

Inline functions are normally treated like instructions, causethe compiler will insert inline functions directly into theprogram and optimise it very strong. So a allocation betweeninstructions of the program and the source code of the inlinefunction is impossible. For testing of a program teh compileroption “Don´t inline“ can be set and the compiler willtreat every inline function like a normal one. So inlinefunctions can be single stepped.

The menu item "Step in" in the "Debugger" menu has thesame effect.

Step over (single step, but execute function calls without stopping)This step will always go to the next breakpoint button visiblein the source code, but function calls are executed at fullCPU speed. If there is a breakpoint the program willnaturally be halted.

The menu item "Step over" in the "Debugger" menu hasthe same effect.

Go to the end of the function.The program will be single stepped until the currentfunction returns to its caller. Function calls are executed atfull speed.

The menu item "Go to end of function" in the"Debugger" menu has the same effect.

Show Current Program PositionThis is the position after the last step or after reaching abreakpoint. When the source code position in th eeditor islost, e.g. by viewing the source code position of a variabledefinition, it can be displayed by this button.

Normally the debugger displays all source sin the sameeditor window. At every change of it the old on will beremoved out of memory and the new one is loaded. so thenumber of open windows can be minimised.

StormC User Manual 171

Page 172: StormC V3 Users Manual

7 THE DEBUGGER◆

In cases a source is used very often it is sensible to keep itopen permanently. So it must be opened by a double clickon its entry in the project and not on the one in the modulewindow. When the text is need the next time thebreakpoints are automatically added. This way two or moresource windows can be used.

The item “Show PC“ of the “Debugger“ menu has the sameeffect.

PauseStops the program while the button is lowered. The programwill be removed from the list of running or waiting tasks.Processing of signals received while the program was pausedis not guaranteed.

The menu item "Pause" in the "Debugger" menu has thesame effect.

KillThe program will be halted abruptly. No care is taken thatthe program isn’t executing within a "Forbid()" -"Permit()", or hasn’t got a screen "locked". "Kill" istherefore not safe under all circumstances.

The menu item "Kill" in the "Debugger" menu has the sameeffect.

Priority gadgetsThe program priority can be altered from "-128" to "127", itis however recommended to leave the priority in the "-20" to"20" range, to avoid conflicts with certain OS tasks.

Normally the priority is set to "-1" so it is one time lower thanthe priority of the debugger and it will run perfectly.

Signal groupThe signals <Ctrl>-<C>, <Ctrl>-<D>, <Ctrl>-<E> and <Ctrl>-<F> can be send at any moment. They are useful for simpleprogram control while testing.

Protocol gadgetsThe list itself shows all resources, for which nocorresponding "free" statement was executed. By doubleclicking a line you can show the source code position of the

172 StormC - the professional choice

Page 173: StormC V3 Users Manual

Control Window◆

allocation, if this particular OS function is called directly inthe program, i.e. if the functions are defined by "#pragmaamicall" or "#pragma tagcall".

The screen is flashing when there is no corresponding sourceposition for the resource. Typical resources without acorresponding source position are memory blocks andshared libraries. These resources are reserved by "storm.lib".

To avoid unneeded protocol output only theses resource aredisplayed which reservation was made from the program. Soresources which are directly reserved by a shared library arenot displayed. Maybe one can imagine how many memoryorders an "OpenWindowTags()" will cause...

Resources are freed very carefully. Commonly resources arepointers to a data structure and can a release by another OSfunction can not always be recorded. So there is a test at first,e.g. whether there is a screen with the given data structure"Screen" at the time it should be freed, before the screen willbe closed by "CloseScreen()".

In most cases all resources can be freed.

The menu item "Free resources" in the "Debugger" menufrees all resources.

Window close gadgetThe window will automatically be closed, when the programis ended and all resources are freed.

Closing the window automatically frees the resources.

StormC User Manual 173

Page 174: StormC V3 Users Manual

7 THE DEBUGGER◆

Current variable windowThe variable window shows all variables and inspectedvariables. It can be opened at any time by the item"Variables…" in the "Windows" menu.

Every variable is displayed with its name, type, memory classand value, e.g.

counter <LONG, stack> 42

The type is always displayed in the Amiga typical manner:"LONG" instead of "long int" and "UBYTE" instead of"unsigned char".

The memory class rough marks the place where the variableis stored. The good optimisation of the compiler will oftenput variables to the same register or to temporary unableregisters. So you should not wonde3r when a variable withthe memory class "D0" will always change its value. Thisregister is used very often.

List of memory classes:

"far data" A global variable in the far data model.

"near data" A global variable in the small data model with a4.

"near data (a6)" A global variable in the small data model with a6.

"stack" A local variable or a function parameter on the stack.

"D0" to "D7", "A0" to "A6", "FP0" to "FP7"

A variable in the relevant data, address or FPU register.

174 StormC - the professional choice

Page 175: StormC V3 Users Manual

Current variable window◆

The values of these variables are displayed in the convenientC syntax. Many values can be interpreted differently so theywill be displayed in more than one kind:

Integers are displayed decimal and hexadecimal. Signedtypes ("LONG", "BYTE" …) are displayed decimal with signand hexadecimal without it. "UBYTE" and "BYTE" (also"unsigned char" and "char") are interpreted as ANSIcharacters when there is no control character.

Floating points are only displayed in decimal. When theyshould be showed binary the hex editor must be used.

Counted types are displayed by their value and the name ofthe constant.

Pointers are displayed hexadecimal. The address is followedby an arrow "->" and the value at which the pointer shows.If the pointer shows to "UBYTE" or "BYTE" it will beinterpreted as a pointer to a string and the first 40 characterswill be displayed additionally.

Structures and arrays are displayed with parenthesis and theincluded elements. To limit the length of a value of a structor array the numbers are viewed decimal, pointers only withthe hexadecimal address and nested structures and arraysonly with the parenthesis "{…}". Inspection allows a closerlook at the values of these elements.

HelpIn the first line at the top short help texts will show themeaning of the icons.

Shows all variables and parameters of the current functionand also the global variables of the module of this function.

Shows the global variables of all modules. Variables whichare only defined "extern" are not displayed

Shows all watched variables.

This list can contain any variable or elements of aninspection. However the value of them is not always valid,e.g. register variables are only valid in certain areas of thefunction and variables which are on the stack are only validas long as the program is in this function.

StormC User Manual 175

Page 176: StormC V3 Users Manual

7 THE DEBUGGER◆

Shows the definition of the selected variables in the sourcecode. The source code will be loaded and the cursor ispositioned on the variable definition.

Displays the member function of the selected variables in anew window. In C++ only variables with a struct or class typecan have member functions.

Inspects the selected variable. Therefor the current list of thevariable (which can be an inspection itself) is replaced by alist of the elements of the variable.

If the variable has a struct, union or class type all membersare displayed. If it has an array type the single fields of thearray are showed. If it has a pointer type the type of thispointer is shown.

At a nested inspection the previously set inspection isdisplayed newly. Otherwise the variables that were shownbefore the inspection are displayed (current, global orviewed ones).

Opens the hex editor and positions the cursor on the addressof the selected variable.

Puts the variable to the list of watched variables.

Deletes the variables from the list of watched variables.

Cast Allows changing the type of a variable. The original type willstill be shown in the type list of the window, the valuehowever will be shown according to the new type.

By clearing the string gadget you can set it back to theoriginal type.

The type entered must match the way the debugger writesthem. Only simple types in Amiga specific form ("BYTE","LONG", "DOUBLE"), pointers to these types ("BYTE *", "LONG*" etc.) and all types that are defined anywhere in themodule are allowed.

Value Numeric types allow direct modification without having toresort to the hex editor. The input can be decimal, octal orhexadecimal in the usual C syntax.

176 StormC - the professional choice

Page 177: StormC V3 Users Manual

The module window◆

Strings can be changed too. That means a memory area onwhich a pointer on UBYTE or BYTE shows can be filled witha new string. It cannot be checked if the new string is toolong, that means that the memory behind the reservedbuffer of the old string will be overwritten (!).

The module windowThe module window lists all the modules in the program.This window can be opened anytime using the menu item"Modules" in the "Windows" menu. By double clicking amodule name in this list the source code for this module willbe shown.

Modules without a debug file will not be displayed in thenormal text colour (black) but in the selection colour (blue).

Loads the module source code into the editor.

Displays all functions of the module in a new window.Member functions are displayed with their qualified name,that means the name of the struct or class to which thefunction belongs will be displayed with two leading colonsbefore the function name (e.g. "String::left").

SortingAt the beginning the modules are displayed unsorted, thatmeans they are in the order they appear in the project. Withthis option they can be sorted alphabetically.

StormC User Manual 177

Page 178: StormC V3 Users Manual

7 THE DEBUGGER◆

The function windowThe function window is similar to the module window, butinstead shows the functions in a module or the memberfunction of a C++ class.

similarly a double click in this window will show the sourcecode, only now the cursor is positioned at the start of thefunction. This is a comfortable way of setting breakpoints onfunctions.

The history windowThe last actions of a program are recorded in the historywindow. So you can have a look at the course of yourprogram in the source, e.g. when an unexpected behaviourappears and you do not know why.

The history window can also be opened by the item"History..." in the "Windows" menu.

178 StormC - the professional choice

Page 179: StormC V3 Users Manual

The breakpoint window◆

A double click on an entry will display the source code in theeditor.

Displays the source in the editor.

Deletes all entries of the history. This should be done beforewatching a critical situation.

EntriesThis sets the maximum number of entries in the history. Thevalue must be between 10 and 256.

The breakpoint windowAll set breakpoints are displayed in this window. Thewindow can also be opened by the time "Breakpoints…"in the "Windows" menu.

A double click will display the breakpoint sin the editor.

Displays the breakpoints in the editor.

Toggles breakpoints on or off.

Deletes a breakpoint.

Deletes all breakpoints.

SortingNormally all breakpoints are displayed in order they wereset. The sorting can be switched to alphabetical, where thefirst criterion is the module name and the second is the linenumber of the breakpoint.

Pay attention on breakpoints that are in program parts thatare used by different tasks simultaneous, e.g. a dispatcher ofa BOOPSI gadget. Such a dispatcher is used by the programand by the task "input.devide" (if the gadget is part of an

StormC User Manual 179

Page 180: StormC V3 Users Manual

7 THE DEBUGGER◆

open window). A breakpoint in the dispatcher could lead toan exception in the "input.device" and so cause a systemcrash.

The address requesterIn the "Debugger" menu you can open an address requesterusing "Find address". This shows the current addresses inthe program in two forms and allows you to enter a newaddress in one of the two forms and find its position in thesource code.

Address This string gadget contains the address in its usual form.

Hunk This string gadget contains the hunk of the program wherethe address resides.

Offset This string gadget contains the offset relative to the hunk ofthe program where the address resides.

Search Finds the source code position for the entered address, forexample the hunk/offset pair.

Cancel Closes the requester.

Every program on the Amiga consists of at least on hunkwith number 0. Further hunks have increasing numbers.Every address that lies within a program corresponds exactlyto a hunk and an offset, likewise every hunk/offset paircorresponds to an address, when you’re searching one in aprogram.

Many debugging-related programs use this form, sincecontrary to a physical address, the form hunk/offset is thesame for every start of a program, whereas physical addressesmay change each time.

As soon as you change any of the three values, an attempt ismade to re-compute the other form. When you’re lookingfor a particular hunk/offset pair (for example after yourprogram caused an enforcer hit), this is an easy way to find

180 StormC - the professional choice

Page 181: StormC V3 Users Manual

The hex editor◆

the physical address and subsequently the source codeposition using "Search".

The hex editorThe hex editor shows an area of memory in hexadecimal andas ASCII characters. The display can be byte, word or longword based.

Choosing the displayThis pop-up allows you to choose how to display thehexadecimal values. Byte, word and long word can beselected.

The address string gadgetThis string gadget shows the current address under thecursor or allows you to set a new address.

The address columnIn this column the address of the first byte of each line willbe shown. These addresses can be changed directly as well,no need to switch to the address string gadget.

The hexadecimal columnThis column displays the hexadecimal value the memorylocations. If the address points to an illegal memory areathen only minus characters are displayed and everymodification is suppressed. The memory locations are notread to avoid enforcer-hits.

The ASCII columnThis column displays the ANSI-character for the memorylocations. If the value is outside the range of displayableANSI characters a dot is shown, likewise for illegal memoryaddresses.

StormC User Manual 181

Page 182: StormC V3 Users Manual

7 THE DEBUGGER◆

Keyboard controlThe four cursor keys move the cursor within a column.

The <Tab> key switches to the next column.

In the address and hexadecimal columns the keys ‘0’ to ‘9’and ‘a’ to ‘f’ (and these also with <Shift>, i.e. ‘A’ to ‘F’) areallowed.

In the ASCII column every character that is displayable oneway or the other is of course allowed.

The scrollbar in the hex editorTo allow for comfortable operation of the scrollbar the totalarea covered by it is constrained to 8 Kbytes. However, if youmove the mouse over the top or bottom border of the hexeditor display the current address will be moved 4 Kbytes upor down, respectively. This allows you to also examine largerareas using the scrollbar.

For really big changes to the address it is always better todirectly enter the address, because of the large address spaceof the CPU.

182 StormC - the professional choice

Page 183: StormC V3 Users Manual

StormLink8 ◆

8 The Linker

n a compiler system one rarely works with just a single source text. Splittingup a project in multiple parts becomes unavoidable after some time, be it tofacilitate maintenance or because there is more than one programmer

involved. An additional reason for dividing a project into several source files is highercompilation speed; recompilation after changing a single source file is faster as the othersources need not be processed again.

After compiling a multi-part project the linker is called upon, first, to combine the partsinto a single program and second, to glue in the function libraries that high-levellanguages, particularly C and C++, tend to rely upon.

Two kinds of libraries exist in the Amiga system: Shared libraries, which are loaded atrun-time and can be used by more than one program at the same time, and link librariessuch as the standard ANSI library and the C++ class library which are attached (linked)directly to the program.

THE LINKER, THE UNKNOWN CREATURE ................................................. 185

A first example ............................................................................................. 185ANSI-C Hello World .......................................................................................... 185

Startup Code ................................................................................................. 186

Usage ................................................................................................................ 189

Parameters ..................................................................................................... 189

Memory classes ............................................................................................. 191

Compatibility ................................................................................................ 200

Error Messages ............................................................................................. 200

Error Messages ............................................................................................. 201Unknown symbol type ...................................................................................... 20116-bit Data reloc out of range ......................................................................... 2018-bit data reloc out of range ............................................................................ 201Hunk type not Code/Data/BSS ......................................................................... 20116-bit code reloc out of range .......................................................................... 2018-bit code reloc out of range ............................................................................ 201Offset to data object is not 16-bit .................................................................... 201Offset to code object is not 16-bit .................................................................... 202Offset to data object is not 8-bit ...................................................................... 202Offset to code object is not 8-bit ...................................................................... 202

I

StormC User Manual 183

Page 184: StormC V3 Users Manual

8 THE LINKER◆

Data- access to code .........................................................................................202Code- access to data .........................................................................................202InitModules() not used, but not empty .............................................................202CleanupModules() not used, but not empty ......................................................203File not found ....................................................................................................203Unknown number format .................................................................................203Symbol is not defined in this file .......................................................................203Nothing loaded, thus no linking .......................................................................203Can not write file ..............................................................................................203Program is already linked .................................................................................204Overlays not supported .....................................................................................204Hunk is unknown ..............................................................................................204Program does not contain any code .................................................................204Symbol not defined ...........................................................................................204Symbol renamed to _stub .................................................................................204_stub is undefined .............................................................................................20532-Bit Reference for Symbol ..............................................................................20532-bit Reloc to Data .........................................................................................20532-bit Reloc to BSS ............................................................................................20532-bit Reloc to Code .........................................................................................20532 Bit Reference for symbol from FROMFILE to TOFILE .....................................205Jump chain across hunk > 32 KByte not possible ..............................................205More than 32 KByte merged hunks ...................................................................205Illegal access to Linker-defined Symbol .............................................................205Fatal errors : aborting ......................................................................................206Hunk_lib inside Library .....................................................................................206Hunk_Lib not found ..........................................................................................206Wrong type in Library .......................................................................................206

Predefined values ........................................................................................206Symbols for data-data relocation .....................................................................208Hunk Layout .....................................................................................................208Memory Classes ................................................................................................208

Order of Searching for Symbols ............................................................209

Hunk Order .....................................................................................................209

Near Code / Near Data ..............................................................................209

184 StormC - the professional choice

Page 185: StormC V3 Users Manual

A first example◆

THE LINKER, THE UNKNOWN CREATURE

The StormC package comes with an integrated linker calledStormLink. This subprogram does a lot more than merelycombine program and library modules, as will be explainedbelow.

It is common practice in high-level languages to divide evenrelatively small projects over several modules. As mentionedin the introduction large benefits are to be had here; reducedcompiler turnaround times and more manageable sourcefiles are only two examples.

Frequently-used routines may be combined into librariesand reused at will. These libraries may grow quite large,however the linker will only glue in the functions that areactually used, enabling wide standardisation and reuse offinished code without the need for translating it anew eachtime it is used.

A first exampleShould you be unfamiliar with these concepts, allow me toexplain them with an example. We shall use our well-knownexample program in ANSI-C:

ANSI-C Hello World#include <stdio.h>int main( void){printf( "Hello World\n");return 0;}

The text output function used here is called printf(). Nowif you create a project ANSIWORLD.¶, and add only a filecontaining this little program (let’s call it ANSIWORLD.C), youmay compile and run it in the familiar way. The program willprint "Hello World"; yet the printf() function has notbeen defined anywhere in your code.

So, where does this function come from and what does itscode look like?

StormC User Manual 185

Page 186: StormC V3 Users Manual

8 THE LINKER◆

Actually the programmer need not concern himself withthat. The function "printf()", with many others, belongsto the standard ANSI library that we have alreadyprogrammed for you and included in the compiler system.

In most compiler systems, each program must eventually berun through a linker, which finds and includes any routinesthat the programmer may have used, to produce a workingexecutable. How this is done internally isn’t normally of anyinterest. What matters is how to make your wishes known tothe linker, and how to configure the linking process to yourneeds.

Startup CodeSome internal tasks that need to be performed by anyprogram upon startup, and some cleanup work whenexiting, are handled for you by startup code that is includedautomatically by the linker. StormC comes with twovarieties of this module called "startup.o" and "library–_startup.o" (both can be found in the "StormC:–StormSys" drawer).

You will only need the "library_startup.o" startup codewhen programming shared libraries; it contains certaintables and other data structures necessary for initialisingshared libraries such as the "_SysBase" variable, which the"LibInit()" function uses to keep the "exec.library"base pointer in. This module is used when "Link as SharedLibrary" and "StormC Startup Code" have been selectedin the "Linker 1" page of the Linker Settings window.

The normal startup code is more interesting. It in turn comesin three flavours: One for the "large" data model, and two forthe "small" data model (relative to a4 and to a6, respectively).However the linker will select the appropriate one of thesethree automatically.

All versions of the startup code detect whether your programis started from the CLI or from Workbench, and actaccordingly. In the former case, the startup code first calls"InitModules()", then the function labeled "main_" (thisis the parameterless version of "main" in C++) and finally"CleanupModules()".

In the later case, it first receives the Workbench startupmessage, then calls "InitModules()", and next the

186 StormC - the professional choice

Page 187: StormC V3 Users Manual

Startup Code◆

function labeled "wbmain_P09WBStartup" (this is theversion corresponding to "wbmain(struct WBStartup*)"in C++); finally it calls "CleanupModules()" and replies theWorkbench startup message.

In order to support ANSI C, the "storm.lib" librarycontains standard functions that redirect the calls to "main":

The standard "main_" function parses the CLI command-line arguments and stores them in an array which is thenpassed on to a function labeled "main__iPPc", which is theC++ function "main(int, char **)". If no such functionexists, the ANSI-C "main()" function is called. This functionat least must be defined; otherwise the linker will emit anerror.

The standard function "wbmain_P09WBStartup" simplycalls "_wbmain", which is the ANSI-C function"wbmain(struct WBStartup *)". Should there be nodefinition of this function, the program exits. As a result,starting a CLI-only program from the Workbench will exitquietly instead of causing a system crash.

These functions are all defined in the "storm.lib" libraryand may be overloaded if desired, for instance to make"wbmain()" print an error message if the program cannot berun from the Workbench.

The startup code module defines the following symbols:

_exitThe ANSI-C "exit()" function. This will call"CleanupModules()" and subsequently exits the programcorrectly.

abort__STANDARDThe "abort()" function used if no alternative has beenconfigured using the "signal()" function. It exits theprogram without calling "CleanupModules()". Exiting aprogram in this way makes little sense as libraries will not beclosed and other resources, eg. allocated memory, will not befreed. The use of "exit()" is preferred.

_SysBaseThis is where the "exec.library" base pointer is stored. Itcontains the same value found at the absolute address "$4",but is used to reduce the number of accesses to that memoryarea.

StormC User Manual 187

Page 188: StormC V3 Users Manual

8 THE LINKER◆

Should you plan to write your own startup code, please takecare to define these symbols if you want to use the"storm.lib" link library. The compiler itself expects certainfunctions in this library, for example those that perform 64-bit integer arithmetic, to be defined so you need to link with"storm.lib" if you intend to use that. However thesefunctions do not depend on any of the above-mentionedsymbols.

The small-data model versions will additionally copy theprogram’s static data area to dynamic memory if theprogram is linked with the options "ResidentableProgram" and "Write Reloc-table For Data To Data"enabled. This will make the program residentable and(usually) re-entrant, so that it can be loaded into memorywith the "resident" CLI command and run several timesconcurrently.

In addition to the possibility of defining your own startupcode, you may also opt to use no startup code at all. If youchoose to do this, you should include as a first source file inthe project a small file containing only a minimal functionthat simply calls the real entry point of the program.

Example:

void pre_main(int, char *);

void my_startup(register __d0 int cmdlinelen, register __a0 char *cmdline)

{pre_main(cmdlinelen,cmdline);

}

The first source file in the project should contain no morethan this.

The necessity for this really quite pointless function is thatthe order in which functions are defined in the object fileneed not match the order in which the source file definesthem, and the executable file may put them in yet anotherorder.

The only guarantee that StormC makes here is that the firstfile in a project will be the first one to be passed to the linker(provided of course that you link without startup code)

188 StormC - the professional choice

Page 189: StormC V3 Users Manual

Usage◆

which will use the first code hunk in this file as the entrypoint of the executable.

Larger source files than the one shown above, with multiplefunctions and perhaps global variables (whether static ornot) and include files could have the code for the functionsin a different order than you may expect, eg. the "INIT_"and "EXIT_" functions for global variables in C++ are oftenput at the start of the object file. But even in ANSI-C thecompiler will sometimes generate such "INIT_" functions,e.g. to initialise complex data structures.

UsageThe user normally doesn not see the linker, as it is called byStormC’s integrated development environment. Startedfrom CLI, StormLink will evaluate its command line and, ifit contains only a single parameter "AREXX", attempt toestablish an ARexx message channel to a port called"STORMSHELL".

ParametersStormLink supports the following command-line options:

TOSelects the output file name.

UsageTO "filename"

DescriptionStormLink does not check if a file of the same name alreadyexists; if it does, it will be overwritten without asking. If morethan one output file has been selected, the last one will beused.

MAPUsage

MAP

DescriptionThis option causes StormLink to create a file called a "linkermap" containing all symbols in the created program andtheir place within the executable. Here is an extract fromsuch a linker map:

_cout = $ 24 in hunk 1 <stormc:lib/storm.lib> ( Far Public )_std__out = $ 32 in hunk 1 <stormc:lib/storm.lib> ( Far Public )_std__in = $ 16 in hunk 1 <stormc:lib/storm.lib> ( Far Public )

_cin = $ 8 in hunk 1 <stormc:lib/storm.lib> ( Far Public )_clog = $ 40 in hunk 1 <stormc:lib/storm.lib> ( Far Public )

_std__err = $ 4E in hunk 1 <stormc:lib/storm.lib> ( Far Public )_cerr = $ 40 in hunk 1 <stormc:lib/storm.lib> ( Far Public )

StormC User Manual 189

Page 190: StormC V3 Users Manual

8 THE LINKER◆

The first entry in every line contains the name of a symbol,followed by its offset in hexadecimal notation, and thenumber of the hunk in which it is defined; next, the nameof the object file that the symbol originates from and finallyits memory class.

LIB Selects the linker’s search path.

Usage LIB | LIBRARY

Description Any object files specified after this option are opened underthe names used on the command line; if they are not found,the linker looks for them in the "StormC:LIB" directory(this may be changed with the LIBPATH option). Failing this,it will see if that directory contains a file of the same libraryname but with ".lib" appended. Failing this, an error isreported.

LIBPATHUsage LIBPATH

Description With this option you may configure where StormC looks forits library files. The default is "StormC:LIB".

CHIP Sets the memory class for the finished program.

Usage CHIP

Description Forces the entire program to be loaded into Chip memory.

FASTUsage FAST

Description Forces the entire program to be loaded into Fast memory;this is the opposite to CHIP.

CAUTION! Attempting to run a program linked with the FAST option onan Amiga that has no Fast memory will result in anAmigaDOS error 103 (out of memory).

190 StormC - the professional choice

Page 191: StormC V3 Users Manual

Memory classes◆

Memory classesThe Amiga architecture defines two types of RAM, to witChip and Fast memory. This distinction is made for reasonsof efficiency.

Any data to be processed by the Amiga’s custom chipset, eg.sound samples or sprite bitmaps must reside in Chipmemory. This memory is shared between the processor andthe chipset which accesses it continually, resulting in asignificant slowdown for CPU access.

Depending on screen mode and DMA activity by e.g. theblitter, the processor may be restricted to use only as little asone fourth of the total bandwidth of this part of memory.For this reason most Amiga models come with additional so-called Fast-RAM, which is reserved for use by the CPU andwhich therefore sustains much higher access speeds. Inaddition it is usually run at a higher clock speed than Chip-RAM, increasing bandwidth even further. Program codeshould therefore preferably be loaded into Fast-RAM, ifavailable; Chip memory should only be used when strictlynecessary.

Fortunately the Amiga OS allows the programmer to specifywhat type of memory each program section (Glossary->Hunk) requires. This makes it possible to load a programinto Chip memory specifically, should this becomenecessary. Usually however only small parts of the programneed to reside in Chip-RAM. They can be compiled/assembled separately, or StormLink may be instructed to addthe necessary directives to these parts of the program shouldthey be missing in the object file. Note that StormLinkcannot do this as selectively as the programmer could, usingthe "#pragma chip" directive. The following options can beused to make StormLink force all data, code or BSS sectionsinto Chip or Fast memory respectively.

Please keep in mind that program code in Chip-RAM will runat no more than one-fourth the speed it would have in Fast-RAM.

StormC User Manual 191

Page 192: StormC V3 Users Manual

8 THE LINKER◆

CHIP Enables CHIPCODE, CHIPDATA and CHIPBSS.

Usage CHIPCODE CHIPDATA CHIPBSS

Description These force the OS to load the indicated program sectionsinto Chip-RAM.

For example, CHIPDATA may be needed when somegraphical objects fail to appear on the screen. This option isto be used with caution as it causes all data to be loaded intoChip-RAM.

FAST Enables FASTCODE, FASTDATA and FASTBSS.

Usage FASTCODE FASTDATA FASTBSS

Description These options are really only provided for sake ofcompleteness, as using them forces the specified sectionsinto Fast-RAM and the resulting program cannot be run ifnone is available. They may be useful in some cases though,as the OS will attempt to flush unused libraries from memoryif necessary to free up Fast-RAM, rather than simply load theprogram into Chip-RAM. These options were included for noother reason.

ADDSYM Create symbol hunks (HUNK_SYMBOL data)

Usage ADDSYM

Description This option copies symbol information from the object fileinto the output file, so that labels seen in a debugger willhave meaningful names. StormLink also includes globalsymbols, so in some cases the name for a particular addressmay be included twice.

DEBUGUsage DEBUG

Description Generates a ".LINK" file needed by the StormC system to run theprogram through the debugger.

192 StormC - the professional choice

Page 193: StormC V3 Users Manual

Memory classes◆

ROMCODEUsage

ROMCODE CodeStart DataStart BssStart

DescriptionFor those who want to create EPROMs; use this option only if youreally know what you’re doing.

The output file will contain only the raw code and datahunks. The BSS hunk must be allocated manually at theappropriate absolute address using the "AllocAbs()"function. Code and data hunks are relocated to the specifiedaddresses at compile time, so there is no AmigaDOSrelocation table overhead. After the indicated number ofbytes of code, only the data section follows.

Caution!If your program addresses data relative to an address register,the BSS hunk is again assumed to be directly behind the datahunk. The BSS thus starts at Address of Data + Length ofData. The SmallCode, SmallData and SmallBSS are setautomatically, so there is no fragmentation. Using theWARNREL option and corresponding startup code you mayproduce completely PC-relative code here.

BASELinker database offset

UsageBASE number

DescriptionSets the linker database’s offset value within the program toFirst Data Object + number. Should your program containtoo much data, resulting in a "16-Bit Reference/Reloc Out ofRange" error from the linker, setting BASE to 0x8000 mayhelp you out. If this doesn’t work, you will need to switch to32-bit addressing.

ONEHUNKGenerates CODE hunk only

UsageONEHUNK

DescriptionProduces a single CODE hunk containing all Code, Data andBSS sections. This could be useful for games programmers.

Any relocation routine now only needs to deal with onehunk. If the program is compiled with the Small Data model,this allows completely PC-relative programming in a high-level language. The data base register (normally a4) is nowinitialised with

lea _LinkerDB(PC),a4

StormC User Manual 193

Page 194: StormC V3 Users Manual

8 THE LINKER◆

If all other addressing is done using d16(pc) or d16(a4), theprogram will be entirely free of absolute addresses.

Such programs are fast in loading, but are normally non re-entrant. Combining this option with ROMCODE yields aprogram that can be loaded into some (SPECIFIC) absoluteaddress using Read(File, Buffer, len), and run directly.This technique requires that the program contains noabsolute addresses whatsoever, meaning that the WARNRELoption must be enabled if you want to apply it.

VERBOSE Enables the multiple-definition check.

Usage VERBOSE

Description If VERBOSE is enabled, StormLink shows the names of anyfiles loaded and scans them for multiply-defined symbols.Should one be found, it will print the names of the objectfiles that define it.

The check also applies to libraries, as names can be usedmore than once there but with different meanings.

Perhaps the best example of this is the C printf() function:The "MATH.LIB" library defines a second version of thisfunction, which is capable of printing floating-pointnumbers. The VERBOSE option is disabled for filenamesfollowing the LIB keyword, so that the program may stilloverload library symbols.

SMALLCODE, SMALLDATA, SMALLBSS

These options are superfluous under normal circumstances,as StormLink can independently decide what to do with ahunk. In some cases however this may not be what youintended, which is why these options allow you to influencehow the linker combines the hunks.

These options take priority over and disable their respectiveMAXCODE, MAXDATA and MAXBSS counterparts.

194 StormC - the professional choice

Page 195: StormC V3 Users Manual

Memory classes◆

SMALLCODEForces creation of only a single Code section.

SMALLDATASMALLBSSDescriptionSpecifying any of these options causes only a single hunk of

the corresponding type to be generated. It will obey thestrictest of the memory-class constraints for that hunk type.

See alsoMemory classes

MAXCODEMAXDATAMAXBSSUsageMAXCODE number

MAXDATA numberMAXBSS number

DescriptionStormLink normally merges all hunks of the same type, e.g.all NEAR hunks, all PUBLIC-CODE hunks, and so on, into onehunk for each type.

Using these options you may fragment the program, i.e.create several smaller hunks of the same type. StormLink willmerge as many hunks as will fit into the size specified.

Specifying MAXCODE 1 will prevent any CODE hunks to bemerged, so each one will appear as a separate hunk in theexecutable. Hunks marked MERGED are an exception; thesewill all be merged into a single hunk regardless.

RESIDENTUsageRES | RESIDENT

DescriptionA program that is to be kept resident in memory makes somespecial requirements of the run-time system. Globalvariables must be kept for each instantiation separately so noother invocation of the same resident program can reach oralter them.

A residentable program is essentially a program with thesmall data model that creates a new copy of its entire datasection on each invocation and uses the copy exclusively.Above all it is vital that the program reference no absoluteaddresses. These would point to the original data section and

StormC User Manual 195

Page 196: StormC V3 Users Manual

8 THE LINKER◆

cannot be redirected to the copy. With the RESIDENTenabled a warning is emitted for such cases.

WARNREL Warn of 32-bit relocations.

Usage WARNREL

Description Causes StormLink to emit a warning if the program contains32-bit Relocs. This option is not to be confused withRESIDENT.

Use this option when creating position-independent code.In that case one should use the ONEHUNK option as well.

OPTIMIZEUsage OPTIMIZE

Description When OPTIMIZE is enabled, StormLink makes anoptimization pass over the object code. If a 32-bit referenceto an object within the same hunk is found, StormLink willattempt to replace it by a PC-relative reference saving 4 bytesby freeing up a reloc entry.

This optimisation may result in incorrect code however. Theoptimiser contains a tiny "disassembler" that recognises onlythe JSR, PEA and LEA instructions. It cannot distinguishbetween code and any data that may be interspersed with it.

The optimiser is only called for global references, ie. whenreferences are bound across object modules. Performingthese optimisations for relocation entries is left to theassembler and the compiler.

NEARCODEDescription StormLink assumes that all symbols needed for

CleanupModules or InitModules can be reached by a singleshort jump. This may lead to problems with very largehunks, as this type of jump cannot cover a distance of morethan 32 Kb.

OOPUsage OOP

Description Generates the auto-init and auto-exit routines needed by aC++ compiler. When enabled, StormLink assembles aroutine labeled "_InitModules" and one labeled

196 StormC - the professional choice

Page 197: StormC V3 Users Manual

Memory classes◆

"_CleanupModules", which call the required "_INIT_x_"and "_EXIT_x_" routines.

Here "x" is a number between 0 and 9. In this case, and onlyin this one, the use of multiple symbols with the same nameis allowed. If the routines are non-empty, yet never called, awarning is emitted.

The "_InitModules" routine calls the "_INIT_0_" routinesfirst, and the "_INIT_9_" routines last. The order is reversedin "_CleanupModules". The entries are sorted by number,where single-digit numbers are multiplied by 100 and two-digit numbers by 10. Thus "_INIT_1_" is called before"_INIT_31_", ensuring compatibility with the three-digitpriority numbers in the SAS/C compiler.

LOGUsageLOG "filename"

DescriptionWhenever a symbol is referenced that StormLink can’t find,an ERROR 25 message is generated. Before this happens,however, it tries to find out which file it could load to findthe symbol anyway.

The LOG option loads a log file, which contains informationabout object files and the symbols defined in them. It lookslike this:

<filename> <= This is the name of the object file <symbol> <= Symbols <symbol> The filenames start at the first column, whereas symbols arerecognised by leading whitespace.

DDRELUsageDDREL

DescriptionThe abbreviation means Data-Data Relocation. If there areany fixed 32-bit relocations from Data to Data/BSS, thisoption instructs StormLink to set up an internal relocationtable for the program so that the startup code can work outthe relocations for its own copy of the Data/BSS hunks. Thisoption is useful only in conjunction with RESIDENT.

StormC User Manual 197

Page 198: StormC V3 Users Manual

8 THE LINKER◆

FORCELINKUsage FORCELINK

Description This option forces StormLink to include all Data and BSShunks from all object files included in the command line.

Unused hunks from libraries are still stripped from theoutput file. Using this option may become necessary if yourprogram contains global classes with constructors thatperform useful work although the objects of those classes arenever used in the program. StormLink would attempt todiscard these objects as unused, which may not be what youintended.

MODELUsage MODEL [ FAR - NEAR - NEAR_A6 ]

Description To simplify library handling, StormLink allows you to ignorecertain parts of a library.

When, for instance, the MODEL option is used with the FARargument all parts compiled with the NEAR or NEAR_A6options are omitted. As a result a library may containmultiple versions of each of its symbols, obviating the needfor a plethora of different versions of each library. With thisoption the linker can be instructed to simply select thedesired version of each function.

FOLDCODEUsage FOLDCODE

Description StormLink is able to perform several optimisations on thefinal executable similar to those performed by a compiler.One of these is detection and removal of duplicated code,which is enabled by this option.

When StormLink finds two identical routines, where onecould be replaced by the other without affecting the result,the second routine is removed and replaced by the first one.

The use of this option may not seem apparent; after all youknow what is in your program and wouldn’t define identicalfunctions. The answer is in C++ template instantiations. Anexecutable may contain many identical instantiations of afunction template or class template member function

198 StormC - the professional choice

Page 199: StormC V3 Users Manual

Memory classes◆

resulting in potentially enormous code bloat anddeteriorated cache performance.

As this optimisation may take some time to perform its useis only recommended when compiling at optimisation level9, and you have either a fast machine or enough time tospare.

VERSIONUsageVERSION "number"

DescriptionSets the global constant _ _VERSION to the numerical valueof "number".

REVISIONUsageREVISION "number"

DescriptionSets the global constant _ _REVISION to the numericalvalue of "number".

ARexx StormLink has an ARexx port called STORMLINK.Although full documentation of this port and its commandscould be of interest to some users, it is too large for the scopeof this manual section.

This port is not intended for use from Rexx. Suffice it to saythat StormLink, when called from the CLI withoutarguments goes into ARexx mode. Four commands aresupported, each of which may however give rise to a floodof communications with StormC’s IDE.

CDUsageCD "name"

DescriptionSets StormLink’s working directory to the directory namedby the argument.

LINKUsageLINK files.o Options...

DescriptionInitiates the linking stage with the specified options andobject files.

BREAKUsageBREAK

StormC User Manual 199

Page 200: StormC V3 Users Manual

8 THE LINKER◆

Description Interrupts an ongoing linking stage, if possible.

QUITUsage QUIT

Description Remove StormLink from memory

CompatibilityStormLink is highly compatible with BLink and with SLinkfrom the SAS/C package. StormLink supports both the SAS/C library format as the SAS/C constructor and destructorfeatures. Combined use with StormC poses no problems, soyou may use them together.

Error MessagesOne design goal for StormLink was proper behaviour undererror conditions. All error messages consist of several parts:First comes either the word "Warning" or the word "Error",followed by the number of the error message. Then comes abrief explanation with some parameters similar inappearance to a command line. This enables you to quicklyfind the necessary information.

The following message parameters may occur:

TYPE This keyword is followed by the type of the hunk in whichthe error occurred, ie. "Code", "Data" or "BSS".

FILE Indicates the object file in which the error occurs.

FROMFILETOFILE As the job of the linker is to combine object files, some errors

are caused by more than one file. In such cases the FROMFILEkeyword indicates the file containing the problematicreference and TOFILE shows the object file it points to.

SYMBOL Shows the name of the symbol involved in the error.

OFFSET Shows the file offset at which the problem occurred.

PREFILE This parameter is printed only in the case of a multiplydefined symbol; it shows the name of the file containing itsfirst definition.

200 StormC - the professional choice

Page 201: StormC V3 Users Manual

Error Messages◆

HUNKTYPEFollowed by a number, this parameter indicates an invalidobject file.

Most of these errors are not fatal and will not cause thelinking stage to be aborted. They are, however, ofimportance with regard to the produced executable as theyindicate that something has gone wrong at the placeindicated in the error message.

Running such an executable will most likely result in asystem crash ! If you are certain that the symbol involved isnever used then doing so is nevertheless still possible, e.g. inthe debugger.

Error MessagesUnknown symbol type

Error 0.This is a symptom of an incorrect object file; it contains asymbol with a type designator that StormLink doesn’t know.

16-bit Data reloc out of rangeError 1.This error can occur when SmallData hunks get too large. If

BASE is already set to its maximum (0x8000) then you havea problem. The program contains too many data for thesmall data model.

8-bit data reloc out of rangeError 2.See error 1; this error has the same cause but should be more

rare.

Hunk type not Code/Data/BSSError 3.This object file is corrupted, if it is an object file at all.

16-bit code reloc out of rangeError 4.Similar to error 1, but for code rather than for data.

StormLink encountered a 16-bit reference spanning too longa distance.

8-bit code reloc out of rangeError 5.See above.

Offset to data object is not 16-bitError 6.The distance to an imported data object is too large.

See error 1.

StormC User Manual 201

Page 202: StormC V3 Users Manual

8 THE LINKER◆

Offset to code object is not 16-bitError 7. This error should never occur. If such a situation occurs,

StormLink will build a chain of short jumps to span the samedistance. Only if even the jump out of the hunk is too longcan this still be a problem.

Offset to data object is not 8-bitError 8. This error is analogous to error 6 with the difference that the

maximum allowed distance is limited to only 8 bits.

Solution Find the corresponding symbol in the map file and set theBASE value manually (between -127 and +127). If errors ofthis kind still occur, getting the program to link is next toimpossible. The only solution is to change the source codecausing the problem.

Offset to code object is not 8-bitError 9. The usual cause for this error are object files created by an

assembler that contain a directive of the form "bsr.s_external_name". This error should not occur with objectfiles created by StormC, as it doesn’t (and mustn’t) use suchconstructs. The indicated object file apparently contains areference to a code object that cannot be resolved.

Solution Rewrite the source code causing the problem.

Data- access to codeError 10. Object files can state whether a reference should point to a

data object or into the code area. If StormLink discovers aviolation of this restriction, it rings the alarm. This error iscaused by such constructs as "extern long printf;printf=0;", which is absolutely fatal to the program! TheVERBOSE option enables this warning.

Code- access to dataError 11. This error is currently disabled as it would give false alarms

continually. I have yet to find an assembler that can generatethe necessary data references and does not use the same typeof reference for code and data all the time.

InitModules() not used, but not emptyError 12. All modules that need any kind of initialisation export a so-

called constructor, and a destructor for cleaning upafterwards.

202 StormC - the professional choice

Page 203: StormC V3 Users Manual

Error Messages◆

StormLink automatically generates code to call theseroutines. The program first calls the InitModules routine,usually from the "STARTUP.O" startup code, which in turncalls all the constructors. If this is not done, ie. if the routineis never called yet does contain code, the program cannot becorrect unless it would call all INIT_xx and EXIT_xx routinesby itself.

Seeing that the linker knows best just what is in the list ofnecessary routines and what isn’t, you shouldn’t even try todo this by hand. In strict accordance to Murphy’s Law, onewill always be forgotten.

CleanupModules() not used, but not emptyError 13.See error 12.

File not foundError 14.The problem is obvious: StormLink can’t find any file with

the name you specify.

Unknown number formatError 15.StormLink has its own parser to recognise and process

different numeric notations such as decimal, octal andhexadecimal numbers in two different formats. This parseris also smaller than its "STORM.LIB" equivalent.Hexadecimal numbers may begin with either "0x" or "$".This error message is displayed when a number contains acharacter that doesn’t belong there.

Symbol is not defined in this fileError 16.StormLink is also capable of reading index files from the

MaxonC compiler, which calls them "LOGFILE". If this fileshould state that some symbol is defined in a particularobject file that hasn’t been loaded yet, but no definition forit is found in that file, this error is displayed.

SolutionCorrect the "LOGFILE" file.

Nothing loaded, thus no linkingError 17.The command-line arguments contain only options, and no

object files. Therefore StormLink can’t create an executable.

Can not write fileError 19.For some reason this output file couldn’t be written to.

StormC User Manual 203

Page 204: StormC V3 Users Manual

8 THE LINKER◆

Redefinition of symbol in file FILE , first defined in filePREFILE

Warning 20. StormLink has found a new definition for a symbol that hasalready been defined. As this can lead to errors that aredifficult to track down, it is advisable to rectify this as soonas possible.

Program is already linkedError 21. Once a file has been linked, it no longer contains most of the

information needed by a linker to operate on it. It is almostimpossible to alter an already linked file in a meaningfulway. For this reason StormLink refuses to load such a file atall.

Overlays not supportedError 22. There is nothing StormLink can do with an object file that

requests an overlay. In this day and age when all computershave megabytes of memory, overlays are no longer of anyuse. Please use a shared library instead.

Hunk is unknownError 23. There appears to be something wrong with this object file.

The field that was expected to contain a valid hunk-typedesignator contains nothing that the linker can recognise.

Program does not contain any codeError 24. After stripping any unused parts of the program, the linker

was left with a file that contained no code at all. Thisprogram can’t do anything.

Symbol not definedError 25. A symbol is used for which no definition can be found. It was

either misspelled or is missing from the used libraries. If themessage has a HINT parameter attached it points at the lastsymbol defined before the error, which is usually the routinethat contains the unresolved reference.

Symbol renamed to _stubWarning 27. Any references to undefined symbols are automatically

diverted to a routine called "stub()". The reason for this isthat you may sometimes want to compile large projectsbefore all routines have been written.

204 StormC - the professional choice

Page 205: StormC V3 Users Manual

Error Messages◆

_stub is undefinedError 28.The "stub()" routine simply doesn’t exist.

32-Bit Reference for SymbolWarning 29.This message is enabled by the WARNREL option. It tells you

that a 32-bit reference exists for a symbol that shouldn’t bethere because of the WARNREL option.

32-bit Reloc to DataWarning 31.This warning is also enabled by the WARNREL option.

32-bit Reloc to BSSWarning 32.Like warnings 29 and 31 above, this warning is enabled by

the WARNREL option.

32-bit Reloc to CodeWarning 33.Like warnings 29, 31 and 32 above this warning is enabled

by the WARNREL option.

32 Bit Reference for symbol from FROMFILE to TOFILEWarning 34.This warning gives the filenames connected by the 32-bit

reference to this symbol. The WARNREL option tellsStormLink it should emit a warning for this case.

Jump chain across hunk > 32 KByte not possibleError 35.A jump chain needs to hop over a hunk that is too large for

a single jump.

SolutionCompile the module that causes the problem with the"Create Library" option.

More than 32 KByte merged hunksWarning 36.A MERGED hunk uses 16-bit addressing, which is limited to

a range of +/- 32 Kb (32768 bytes). This could, but need not,lead to problems.

Illegal access to Linker-defined SymbolError 37.StormLink defines a few symbols of its own for specific tasks.

Should any such symbol be erroneously accessed by the userprogram, this error message is displayed.

StormC User Manual 205

Page 206: StormC V3 Users Manual

8 THE LINKER◆

Fatal errors : abortingError 38. This indicates the occurrence of such serious problems while

linking that StormLink can’t handle them anymore. Tryingto proceed under these conditions would only cause moreproblems, which the linker prevents by aborting the process.No output file is generated.

Hunk_lib inside Library ??Error 39. A file that has already been identified as a SAS library

contains another such identifier within the library contents.StormLink doesn’t understand this and exits.

Hunk_Lib not foundError 40. An important part of a file that has been identified as a SAS

library is missing. This indicates a corrupted library.

Wrong type in LibraryError 41. Symbols are represented differently in SAS library than they

are in standard object files. Types simply added in thenormal way confuse StormLink.

Predefined valuesStormLink defines constant symbols for the linker databaseand for the length of the Data and BSS hunks. Notation iscompatible with that used by BLink 6.7, however BLink willnot show all of these symbols.

_LinkerDBUsage _LinkerDB: (label)

Description Points to the first data element + BASE. With BASE set to 0(this is the default) this points to the first element of the NearData hunk. If the SMALLDATA option is used there may wellbe something before this.

_ _SmallDataUsage _ _SmallData: (label)

Description Points to the first data element + 0x8000; this is used by theMaxonC++ compiler which assumes that BASE is always setto its maximum (0x8000). Mixing object files that assumedifferent BASE settings is possible, but the producedexecutable will crash inevitably.

206 StormC - the professional choice

Page 207: StormC V3 Users Manual

Predefined values◆

RESIDENTUsageRESIDENT: (const) 1

Descriptionset when linking with RESIDENT option; 0 otherwise.

_ _VERSIONUsage_ _VERSION: (const) variable.

DescriptionThis is equal to 0 by default, but can be set with the VERSIONoption.

_ _REVISIONUsage_ _REVISION: (const) variable.

DescriptionThis is equal to 0 by default, but can be set with theREVISION option.

SmallData SymbolsUsage_ _DATALEN: (const)

DescriptionLength of the data area in longwords (one longword equalsfour bytes) of the MERGED hunk.

Usage_ _BSSBAS (label)

DescriptionStart of the BSS section in the MERGED hunk.

Usage_ _BSSLEN: (const)

DescriptionLength of the BSS section of the MERGED hunk, in longwords.

Usage_ _OFFSET: (const)

DescriptionThis equals the offset defined by BASE + the amount of dataplaced before the Near Data section of the Data hunk.

These values are useful when writing a pure-residentprogram. It also allows the startup code to determinewhether the BSS section still needs to be initialised orwhether the program has been linked with the RESIDENToption in which case it must set up a new MERGED hunk. Formore detailed information please read the provided sourceto the startup code.

StormC User Manual 207

Page 208: StormC V3 Users Manual

8 THE LINKER◆

Symbols for data-data relocation_DDSIZE: (const) Length of table (in bytes!)

Description Had this length been measured in longwords, the followingwould no longer work.

_DDTABLE: (label)Description Start address of table. This table is attached to the first Code

hunk. If there is only one code hunk, (_DDTABLE+_DDSIZE)points to the end of the hunk. If no DDREL-option has beenset, _DDSIZE equals zero.

Hunk LayoutAggressive hunk merging is pursued to make the generatedexecutables as small as possible.

Memory ClassesFor the purpose of hunk merging, StormLink assigns asignature to each hunk. This signature contains:

- Hunk type (Code, Data or Bss)

- Memory Class (Public, Chip or Fast)

- Addressing Mode (Near or Far)

Naturally one may also use hunks that have already beenmarked with the Chip or the Fast bit. In that case, prioritiesare as follows:

CHIP (maximum)

FAST

PUBLIC (minimum, regardless of memory class)

Setting the Fast bit isn’t very polite as it requires the presenceof Fast-RAM in the system. CHIP data should be declared asFar if at all possible.

Assembler programmers should address CHIP data with 32-bit addressing only. This allows StormLink to merge suchdata into a single CHIP-DATA hunk. This way the Small Datahunk is free to be allocated in expansion RAM. Using somuch as a single 16-bit access to a CHIP data element

208 StormC - the professional choice

Page 209: StormC V3 Users Manual

Order of Searching for Symbols◆

through the xx(ax) addressing mode will force the entireNear Data hunk into Chip-RAM.

Order of Searching for SymbolsSymbols are looked for first in the Code section, then in theData section and finally in the BSS section. If any symbols arenot found, the log file is inspected to find out which objectfile defines them.

Hunk OrderAll hunks of the same signature are merged together as far asany used options such as SMALLCODE or MAXDATA will allow.As StormLink can and will reorder hunks while linking, oneshould not rely on hunks appearing in the executable in thesame order as they do in the object file. The linker first writesall Code sections, then all Data and finally the BSS sections.However the order in which StormLink processes itsparameters is significant. It first makes a pass over thecommand line to filter out the options, and then attemptsto load all other arguments as object files.

Near Code / Near DataStormLink supports programming in the Near code modelwhere routines are accessed through PC-relative addressingto reduce both execution time and program size.

Near Data consists of a hunk containing all pre-initialiseddata of the program as well as all un-initialised data (BSS).This hunk is addressed in a base-relative fashion, i.e. relativeto a base address register. These accesses also have the speedand size advantage over 32-bit absolute addressing. Shouldthe Near Code hunk grow larger than 32 Kb, StormLinkconstructs jump chains across single hunks to allow calls tospan distances larger than 32 kilobytes.

Please take due care when using global data contained in theCODE section; the linker has no way of telling such data apartfrom program code. It may insert intermediate jumps wherea data access was required, which could lead to bugs that areextremely hard to find.

StormC User Manual 209

Page 210: StormC V3 Users Manual

8 THE LINKER◆

210 StormC - the professional choice

Page 211: StormC V3 Users Manual

Index◆

Symbols##base 125

##bias 125

##end 126

##private 126

##public 126

#define 72

#pragma header 71

\ 114

__COMPMODE__ 115

__cplusplus 115

__DATE__ 115

__FILE__ 115

__FUNC__ 116

__inline 109

__LINE__ 116

__STDC__ 116

__STORM__ 116

__TIME__ 116

_LibNameString 128

_LibVersionString 128

_stub 204

_wbmain 187

Aamiga.lib 118, 156

Authors 2auto 107

AutoSave 52

CCleanupModules 113, 186

CompilerCLI version 130Options 134Special features 107

Compiler OptionsANSI C or C++ 137Assembler source 136Code model 138Colours and styles 142Core memories 144

Data model 138Definition of symbols 136Error file 142Exception handling 137Include files 137Linker libraries 141Optimisations 138Optional warnings 143Pre-compiled header files 144RunShell 141Special processors 140Summary 145Symbolic debugger 141Template functions 138Treat warnings like errors 144Warnings and errors 141

Constructors 113

Copyrights 2

DDebug Files 76

Debugger 76Address requester 180Breakpoint window 179Changing Values 161Control Window 169Current variable window 174Display member function 176Don´t inline 171Example 157Free Resources 156Free resources 173Freeze the program temporarily 153Function window 178General information 151Global variables 160Halting the program 154Hex editor 181

Keyboard control 182Icons 169Inspect Variables 176Inspection 160Kill 172Local variables 160Module window 177Pause 172Priority 172Protocol 172

StormC User Manual 211

Page 212: StormC V3 Users Manual

INDEX◆

Resource-Tracking 152Sending signals 154Signals 172Single step 170Sorting of Variables 161Task priority 154Temporary Casts 161Variable Window 159Watched variables 160

Destructor 113

EExceptions 75

EXIT_ 113, 117, 128, 189

extern 107

FFD files 125

HHeader Files 71

Hello World 185

history window 178

Homepage 8Hotline 8

IINIT_ 113, 117, 127, 189

InitModules 113, 186

Inline 108

Internet 7

JJoining Lines 114

KKill 154, 163

LLibClose 126

LibExpunge 126

LibInit 126, 186

LibNull 126

LibOpen 126

library_startup.o 186

Licensee 3Linker

_exit 187Compatibility 200Error Messages 200First example 185Hunk Layout 208Hunk Order 209Memory Classes 208Memory classes 191Near Code 209Near Dat 209Predefined values 206

_ _BSSBAS 207_ _BSSLEN 207_ _DATALEN 207_ _OFFSET 207_ _REVISION 207_ _SmallData 206_ _VERSION 207_DDTABLE 208_LinkerDB 206RESIDENT 207

Startup Code 186Linker parameters

ADDSYM 192BASE 193BREAK 199CD 199CHIP 190, 192DDREL 197DEBUG 192FAST 190, 192FOLDCODE 198FORCELINK 198LIB 190LIBPATH 190LINK 199LOG 197MAP 189MAXBSS 195MAXCODE 195MAXDATA 195MODEL 198NEARCODE 196

212 StormC - the professional choice

Page 213: StormC V3 Users Manual

Index◆

ONEHUNK 193OOP 196OPTIMIZE 196QUIT 200RESIDENT 195REVISION 199ROMCODE 193SMALLBSS 195SMALLCODE 195SMALLDATA 195TO 189VERBOSE 194VERSION 199WARNREL 196

Mmain_ 186

main__iPPc 187

NNested Comments 73

OOptimiser 84

Optimising 78

PPhone 8pragma - 110

pragma + 110

pragma amicall 111, 118, 156, 173

pragma chip 111, 191

pragma fast 111

pragma header 71

Pragma instructions 110

pragma libbase 124

pragma priority 112

pragma tagcall 111, 156, 173

Predefined symbols 115

Preface 5Problems 7Profiler 164

protocol list 155

Prototypes 117

Rregister 107

Register parameters 108

Resource-Tracking 151

RunShell 151

SScreenManager 48

Settings 51

Shared Librariesavail flush 129FD files 125Important hints 128Initialisation 127library_startup.o 128Make your own 123Project Settings 125Register Setup 124Setup 123Using 117

Source Level Debugger 151

startup.o 186

static 107

storm.lib 113, 127, 187

StormLink 185

STORMPRAGMAS 73, 118

Stub Functions 118

Support 8

TTechnical support 7Textoptions 95

Thanks 6Tooltypes 47, 94

GOLDED 48HOTHELP 48PUBSCREEN 48QUIET 48SAVEMEM 48

StormC User Manual 213

Page 214: StormC V3 Users Manual

INDEX◆

WWarnings 80

wbmain_P09WBStartup 187

WWW 8

214 StormC - the professional choice