Pro Fortran Power ™ Fortran & C/C++ User Guide Pro Fortran Power Macintosh™ Fortran & C/C++ User Guide

2781 Bond Street Rochester Hills, MI 48309 U.S.A. Tel (248) 853-0095 Fax (248) 853-0108 [email protected] All rights reserved. No part of this publication may be reproduced or used in any form by any means, without the prior written permission of Absoft Corporation.

THE INFORMATION CONTAINED IN THIS PUBLICATION IS BELIEVED TO BE ACCURATE AND RELIABLE. HOWEVER, ABSOFT CORPORATION MAKES NO REPRESENTATION OF WARRANTIES WITH RESPECT TO THE PROGRAM MATERIAL DESCRIBED HEREIN AND SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE. FURTHER, ABSOFT RESERVES THE RIGHT TO REVISE THE PROGRAM MATERIAL AND MAKE CHANGES THEREIN FROM TIME TO TIME WITHOUT OBLIGATION TO NOTIFY THE PURCHASER OF THE REVISION OR CHANGES. IN NO EVENT SHALL ABSOFT BE LIABLE FOR ANY INCIDENTAL, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE PURCHASER'S USE OF THE PROGRAM MATERIAL.

U.S. GOVERNMENT RESTRICTED RIGHTS — The and documentation are provided with RESTRICTED RIGHTS. Use, duplication, or disclosure by the Government is subject to restrictions set forth in subparagraph (c) (1) (ii) of the Rights in Technical Data and Computer Software clause at 252.227-7013. The contractor is Absoft Corporation, 2781 Bond Street, Rochester Hills, Michigan 48309.

ABSOFT CORPORATION AND ITS LICENSOR(S) MAKE NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE SOFTWARE. ABSOFT AND ITS LICENSOR(S) DO NOT WARRANT, GUARANTEE OR MAKE ANY REPRESENTATIONS REGARDING THE USE OR THE RESULTS OF THE USE OF THE SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY, CURRENTNESS, OR OTHERWISE. THE ENTIRE RISK AS TO THE RESULTS AND PERFORMANCE OF THE SOFTWARE IS ASSUMED BY YOU. THE EXCLUSION OF IMPLIED WARRANTIES IS NOT PERMITTED BY SOME STATES. THE ABOVE EXCLUSION MAY NOT APPLY TO YOU.

IN NO EVENT WILL ABSOFT, ITS DIRECTORS, OFFICERS, EMPLOYEES OR LICENSOR(S) BE LIABLE TO YOU FOR ANY CONSEQUENTIAL, INCIDENTAL OR INDIRECT DAMAGES (INCLUDING DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, AND THE LIKE) ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE EVEN IF ABSOFT HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. BECAUSE SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES, THE ABOVE LIMITATIONS MAY NOT APPLY TO YOU. Absoft and its licensor(s) liability to you for actual damages for any cause whatsoever, and regardless of the form of the action (whether in contract, tort, (including negligence), product liability or otherwise), will be limited to $50.

Absoft, the Absoft logo, Fx, and MacFortran are trademarks of Absoft Corporation Apple, the Apple logo, and HyperCard are registered trademarks of Apple Computer, Inc. CF90 is a trademark of Cray Research, Inc. IBM, MVS, and RS/6000 are trademarks of IBM Corp. Macintosh, NeXT, and NeXTSTEP, are trademarks of Apple Computer, Inc., used under license. MetroWerks and CodeWarrior are trademarks of MetroWerks, Inc. MS-DOS is a trademark of Microsoft Corp. Pentium, Pentium Pro, and Pentium II are trademarks of Intel Corp. PowerPC is a trademark of IBM Corp., used under license. Sun and SPARC are trademarks of Sun Microsystems Computer Corp. UNIX is a trademark of the Santa Cruz Operation, Inc. VAX and VMS are trademarks of Digital Equipment Corp. Windows NT, Windows 95, Windows 98, Windows 3.1, and Win32s are trademarks of Microsoft Corp. All other brand or product names are trademarks of their respective holders.

Copyright © 1991-2001 Absoft Corporation and its licensor(s). All Rights Reserved Printed and manufactured in the United States of America. 7.0050101 Table of Contents i

Fortran User Guide Contents

CHAPTER 1 INTRODUCTION...... 1

Introduction to Absoft Pro Fortran...... 1 Absoft Fortran 90/95 ...... 1 Absoft FORTRAN 77 ...... 1 Absoft C/C++ ...... 2

The Macintosh Programmer's Workshop ...... 2

Compatibility...... 3

Conventions Used in this Manual ...... 3

Road Maps ...... 3 Fortran Road Maps...... 4 Macintosh Programming Road Map...... 4

Year 2000 Problem...... 7 Fortran 90/95 DATE_AND_TIME Subroutine...... 7 Unix Compatibility Library...... 7

CHAPTER 2 GETTING STARTED ...... 9

Introduction to MPW and Absoft Pro Fortran ...... 9

Starting an MPW Session...... 9

The MPW Environment ...... 10 Using the Menus...... 11 Using the Worksheet ...... 11 Executing Commands from the Worksheet...... 11 The Commando Interface ...... 12

Working with Source Files ...... 13 Editing Text...... 14

Compiling Code...... 15

Application Basics ...... 16

Ending an MPW Session...... 18

CHAPTER 3 USING THE EDITOR...... 19

The MPW Editor...... 19

Creating Fortran Source Files ...... 19 ii Fortran User Guide

Manipulating Windows ...... 21

Using the Editor Menus ...... 21 File Menu...... 21 New…(aN)...... 21 Open…(aO) ...... 22 Open Selection (aD)...... 22 Close (aW) ...... 22 Save (aS)...... 22 Save as… ...... 22 Save a Copy… ...... 23 Revert to Saved...... 23 Page Setup…...... 23 Print Window...... 23 Quit (aQ) ...... 23 Edit Menu ...... 23 Undo (aZ)...... 23 Cut (aX)...... 23 Copy (aC)...... 24 Paste (aV) ...... 24 Clear...... 24 Select All (aA)...... 24 Show Clipboard ...... 24 Format… (aY) ...... 24 Align ...... 25 Shift Left and Shift Right (a [ and a])...... 25 Find Menu...... 25 Find… (aF) ...... 25 Searching for Line ...... 25 Searching for Text...... 26 Find Same (aG)...... 27 Find Selection (aH) ...... 27 Display Selection ...... 27 Replace… (aR)...... 28 Replace Same (aT) ...... 28 Next Error (a≥)...... 28 Previous Error (a≤)...... 28 Mark Menu ...... 28 Mark… (aM) ...... 29 Unmark… ...... 29 Browse… ...... 29 Alphabetical ...... 30 Window Menu ...... 30 Tile Windows...... 30 Stack Windows ...... 30 Directory Menu...... 30 Show Directory ...... 31 Set Directory...... 31

CHAPTER 4 USING THE WORKSHEET...... 33

The Worksheet Window ...... 33

MPW Commands ...... 34 Command Syntax...... 35 Executing MPW Commands from the Worksheet...... 35 Table of Contents iii

Command Parameters...... 36 Command Terminators...... 37 Accessing the Commando Interface...... 38 Target and Active Windows...... 39 Routing Command Output ...... 39 File Name Generation...... 41 Using MPW Variables...... 42 User-Defined Variables ...... 42 Preassigned MPW Variables ...... 43 Creating Scripts ...... 43 Command Aliases...... 44 Structured Commands ...... 45 Command Execution ...... 45 Special Characters ...... 45 The ∂ Character...... 46 The § Character ...... 46

MPW Command Reference...... 46 commands ...... 46 NewFolder ...... 47 Files ...... 47 Delete...... 48 Duplicate...... 48 Eject...... 49 Flush ...... 49 Move...... 49 WhereIs...... 49 Volumes...... 50 Rename ...... 50 Choose ...... 51 File-related commands ...... 51 SetFile...... 51 Catenate ...... 52 Search ...... 52 Find...... 53 Translate ...... 53 Sort ...... 53 EnTab...... 54 Count ...... 54 Compare...... 55 CompareFiles...... 55 Equal...... 56 Adjust ...... 56 Clear...... 56 Copy...... 57 Help commands...... 57 GetErrorText...... 57 Help ...... 58 MPW Environment commands ...... 58 AddMenu...... 58 DeleteMenu ...... 59 Date...... 59 Set ...... 60 UnSet ...... 60 Directory...... 60 SetDirectory...... 61 Alias...... 61 iv Fortran User Guide

Align ...... 61 Unalias ...... 62 Mark...... 62 Unmark ...... 62 Commando...... 62 DumpFile ...... 63 Request...... 63 GetFileName ...... 64 Confirm...... 64 Alert ...... 64 Quit ...... 64 Shutdown ...... 65 Beep ...... 65 Window commands ...... 65 New...... 66 Open...... 66 Close ...... 66 Print...... 67 Line ...... 67 Target...... 67 File ...... 68 Windows ...... 68 TileWindows...... 68 ZoomWindows...... 68 MoveWindow ...... 69 SizeWindow...... 69 RotateWindows...... 69

CHAPTER 5 USING THE COMPILER...... 71

Compiling Programs ...... 71 Using the Worksheet...... 71 Using the Tools Menu ...... 72

The Absoft Tools Commando Interface ...... 73 Source Files Dialog Box...... 74 Include Path(s) (-I)...... 74 Libraries…...... 76 Unix Compatibility Library...... 76 VAX/VMS Compatibility Library ...... 76 IMSL MATH/STAT Library ...... 76 LAPACK Linear Algebra Library ...... 77 Other Libraries…...... 77 Text Boxes...... 77 Executable Filename...... 77 Command Line Box...... 78 Help Box ...... 78 Buttons and Compiler Options ...... 78 Output File Box...... 78 Main Program Box...... 79 The Compile Button...... 79 General Option Buttons ...... 79

Errors While Compiling ...... 79 GetErrorText command ...... 80 Table of Contents v

Absoft Fortran 90/95 Options ...... 81 COMPILER CONTROL...... 82 Suppress warnings (-w) ...... 83 Frequent Command-Period checks (-N9)...... 83 Show progress (-v)...... 83 Use 32-bit branches (-N11)...... 83 Output Version number (-V)...... 84 Stop on error (-ea)...... 84 Allow greater than 100 errors (-dq)...... 84 Default Recursion (-eR)...... 84 Use files for temporary storage (-F) ...... 84 Warn of non-standard usage (-en)...... 84 Warning level (-znn)...... 85 Suppress Warning number(s) (-Znn)...... 85 Generate profiler information (-profile) ...... 85 Generate procedure trace (-N80)...... 85 OPTIMIZATIONS… ...... 85 Optimizations (-O)...... 86 COMPATIBILITY…...... 86 Source Formats ...... 87 Free-Form (-f free) ...... 87 Fixed-Form (-f fixed)...... 87 Fixed line length (-W nn) ...... 87 Promote REAL and COMPLEX (-N113)...... 87 Demote Double Precision to Real (-dp) ...... 87 Static storage (-s)...... 87 Disable compiler directive (-xdirective) ...... 88 INTEGER*2 and LOGICAL*2 (-i2)...... 88 INTEGER*8 and LOGICAL*8 (-i8)...... 88 One trip DO loops (-ej) ...... 88 Max Internal Handle (-T nn)...... 89 Temporary string size (-t nn)...... 89 Module File Path(s) (-p)...... 90 Module File(s) (-p)...... 90 MISCELLANEOUS…...... 91 Escape Sequences in Strings (-YCSLASH=1)...... 92 No Dot for Percent (-YNDFP=1)...... 92 COMMON Block Name Character Case (-YCOM_NAMES={ ASIS | UCS | LCS})...... 92 COMMON Block Name Prefix (-YCOM_PFX=string) ...... 92 COMMON Block Name Suffix (-YCOM_SFX=string)...... 92 Check Array Boundaries (-Rb) ...... 93 Check Array Conformance (-Rc) ...... 93 Check Substrings (-Rs) ...... 93 Check Pointers (-Rp)...... 93 YEXT_NAMES={ASIS | UCS | LCS} ...... 93 External Symbol Suffix (-YEXT_SFX=string)...... 93 Other F90/95 Options...... 93 -YDEALLOC= {MINE | ALL | CACHE})...... 94 YPEI={0|1} ...... 94

Absoft Fortran 90/95 Compiler Directives...... 94 NAME Directive ...... 95 FREE Directive ...... 95 FIXED Directive ...... 95 STACK Directive ...... 96

Absoft Fortran 77 Options ...... 96 vi Fortran User Guide

COMPILER CONTROL...... 97 Suppress warnings (-w)...... 97 Suppress alignment warnings (-A)...... 97 Use 32-bit branches (-N11) ...... 98 Generate procedure trace (-N124)...... 98 Generate profiler information (-p) ...... 98 Check array boundaries (-C)...... 98 Full Debug with Fx (-g)...... 98 Min Debug with Fx (-gmin) ...... 98 Info for unused structures (-N111)...... 99 Suppress delayed stores (-m) ...... 99 Conditional compilation (-x)...... 99 Max Internal Handle (-T nn) ...... 99 Output ...... 100 No compiler standard output (-q)...... 100 Show progress (-v)...... 100 Frequent Command-Period checks (-N9) ...... 101 Use files for temporary storage (-F) ...... 101 Define Compiler directives (-Dname[=value]) ...... 101 Generate object files (-c) ...... 101 Specifying the executable file name (-o name) ...... 101 OPTIMIZATIONS… ...... 102 Basic optimizations (-O)...... 102 DATA treated as constants (-N5) ...... 102 Function decomposition (-N18)...... 103 Loop unrolling (-U and -h nn and -H nn) ...... 103 COMPATIBILITY… ...... 104 Folding to lower case (-f)...... 105 Static storage (-s)...... 105 Use record lengths in I/O (-N3) ...... 105 RECL Defines 32-bit words (-N51) ...... 105 Folding to upper case (-N109) ...... 105 One-trip DO loops (-d)...... 106 INTEGER*2 and LOGICAL*2 (-i2 )...... 106 INTEGER*8 and LOGICAL*8 (-i8 )...... 106 Zero extend INTEGER*1 (-N102)...... 106 Warn of non-ANSI usage (-N32) ...... 106 Extern Globals (-M) ...... 106 Source Formats ...... 107 Fortran 90 Free-Form (-8)...... 107 IBM VS Free Form (-N112)...... 107 VAX Tab-Format (-V) ...... 107 Wide format (-W)...... 107 Set Big-Endian (-N26)...... 107 Set Little-Endian (-N27)...... 107 Set COMMON block name (-N22) ...... 107 Evaluate left-to-right (-N20)...... 108 Don’t generate FMA instructions (-Q51)...... 108 Double precision transcendentals (-N2) ...... 108 Sign extend BYTE() & WORD() (-N7) ...... 109 DATA variables are static (-N1)...... 109 Promote REAL and COMPLEX (-N113) ...... 109 Escape sequences in strings (-K)...... 109 Allows CASE without DEFAULT (-N4) ...... 109 Allows UNIT= without FMT= (-N16) ...... 109 Align COMMON variables (-N34) ...... 109 Pascal keyword significant (-N17) ...... 110 Table of Contents vii

Pascal declaration is error (-N21)...... 110 Append underscore to names (-N15) ...... 110 Temporary string size (-t nn)...... 110 STRUCTURE Alignment...... 110 Align STRUCTURE fields to 1 byte boundaries (-N56)...... 110 Align STRUCTURE fields to 2 byte boundaries (-N57)...... 111 Align STRUCTURE fields to 4 byte boundaries (-N58)...... 111 Align STRUCTURE fields to 8 byte boundaries (-N59)...... 111 Other F77 Options...... 111 Warnings for Undeclared Variables (-N114)...... 111 Pad Source Lines (-N115)...... 111 Debug with Fx (-g)...... 111 Don’t Mangle COMMON Block Name (-N110)...... 111

Absoft C/C++ Options ...... 112 Optimizations (-O) ...... 112 Source Formats...... 112 ARM C++ (-Tp) ...... 112 Draft Std C++ (-std)...... 113 ANSI C (-A)...... 113 K and R C (-K)...... 113 COMPILER CONTROL...... 113 Use long branches (-N18) ...... 113 No inlines (-inline none) ...... 114 Use temporary files (!N61)...... 114 Profiler Information (-p)...... 114 Procedure Trace (-N124) ...... 114 Exception Handling (-except on|off) ...... 114 Error and Diagnostic Messages ...... 114 Suppress all warnings (-w31)...... 115 Suppress warnings (-w16)...... 115 Suppress informationals (-w8) ...... 115 Suppress anachronisms (-w2)...... 115 Suppress template warnings (-w1) ...... 115 Treat anachronisms as errors (-wp) ...... 115 Treat all warnings as errors (-wabort)...... 115 Max errors (-maxerr n)...... 115 COMPATIBILITY…...... 116 Suppress Apple extensions (-appleext off)...... 116 Use int enums (-enum min|int)...... 116 Use 68k alignment (-align mac68k|power)...... 116 Make chars unsigned (-char signed|unsigned) ...... 117 Munch…...... 117 Set initialization prefix (-init prefix)...... 117 Set termination prefix (-term prefix)...... 117 PREPROCESSOR…...... 118 Defines (-d name[=value]) ...... 118 Undefines (-u name)...... 118 Preprocess to file (-P)...... 119 Preprocess to stdout (-E) ...... 119 Include tree to stderr (-H) ...... 119 Verbose (-v)...... 119 Verbose templates (-ptv) ...... 119 Quiet (-q) ...... 119

CHAPTER 6 PORTING CODE...... 121 viii Fortran User Guide

Porting Code from VAX ...... 121 Compile Time Options and Issues ...... 122 Runtime Issues...... 123

Porting Code from IBM VS FORTRAN ...... 123 Compile-time Options and Issues ...... 124 Run-time Issues ...... 124

Porting Code From Microsoft FORTRAN (PC version) ...... 124 Compile-time Options and Issues ...... 125

Porting Code from Sun Workstations ...... 126 Compile-time Options and Issues ...... 126

Porting Code from the NeXT Workstation...... 126

Porting Code from the IBM RS/6000 Workstation...... 127

Porting Code from Intel 386/486/Pentium Computers ...... 127

Porting Code To/From Other Macintosh Systems ...... 127 Language Systems Fortran...... 127 Other Absoft Compilers...... 127

Other Porting Issues...... 128 Memory Management...... 128 Stack Issues...... 130 File and Path Names ...... 131 Tab Character Size...... 133 Floating Point Math Control...... 133 Rounding Direction...... 134 Exception Handling ...... 134

CHAPTER 7 BUILDING PROGRAMS ...... 135

An Overview of Program Building ...... 135 The Components of an Application...... 135 Working with Resources...... 136 File types and creators ...... 136

Creating Object Files ...... 136 Fsplit - Source Code Splitting Utility ...... 138 Ftnchek - ANSI Compliance Utility ...... 139

Linking Programs for PowerPC ...... 140

Building Programs...... 143 Creating Makefiles...... 144 Modifying Makefiles ...... 144 Format of a Makefile...... 144 Create Build Commands ...... 145 ACM Command...... 146 Build (aB)...... 147 BuildProgram command ...... 147 Make Command...... 147 Table of Contents ix

The Snowflake program ...... 149

Creating Libraries for PowerPC...... 150

Working with Resources...... 151 Include Files ...... 153 Adding an to an Application ...... 153 The SIZE(-1) Resource ...... 155

Creating a Tool Using Absoft Pro Fortran ...... 156 Tool Initialization ...... 158 Memory Management...... 158

CHAPTER 8 THE MACINTOSH RUNTIME WINDOW ENVIRONMENT..... 159

Using MRWE...... 159 The MRWE Window...... 160 How Your Program And MRWE Work Together ...... 161 Working With Text in MRWE...... 162 Using THE MRWE Default Menus ...... 162 File Menu ...... 162 Save (aS)...... 162 Save As…...... 163 Page Setup… ...... 163 Print Window…(aP)...... 163 Quit (aQ)...... 163 Edit Menu...... 163 Undo (aZ)...... 163 Cut (aX)...... 163 Copy (aC) ...... 163 Paste (aV)...... 164 Clear...... 164 Font and Size Menus ...... 164

Programming with MRWE...... 164 Program Organization: Fortran VS. Macintosh...... 164 MRWE Event Loop Operation ...... 166 Customizing Menus...... 167 Adding Menus ...... 167 Special Characters ...... 168 Menus and the READ statement...... 168 Removing a Menu or Menu Item...... 169 Menu Response Routines and mrwe_DoMenu ...... 169 Adding Checkmarks to Menus ...... 170 Enabling/Disabling Menu Items ...... 170 Launching OTHER APPLICATIONS ...... 171 Apple Events ...... 172 Apple Event Target...... 173 Apple Event Class and ID...... 173 Extra Information in an Apple Event...... 173 Receiving Apple Events ...... 176 Error Codes Returned from Apple Event Routines ...... 179 Other Examples of Apple Events...... 179 Sending a request to the Finder...... 179 Using other standard Apple Events...... 181 Sending information between MRWE applications...... 181 x Fortran User Guide

Scripting ...... 181 Further Information About Apple Events ...... 182 Creating Multiple Windows...... 182 Showing Alert Messages ...... 183 The SetPrefs Tool ...... 184 Applications to affect...... 185 End of execution ...... 185 Window characteristics...... 185 Window name (-savename name)...... 185 Close box (-closebox)...... 185 Window Size (-windowsize normal|maximize) ...... 186 Text characteristics ...... 186 Memory requirements ...... 186 Timer interval...... 187 Timer (-timer 60ths-of-a-second) ...... 187 File characteristics...... 187

CHAPTER 9 MACINTOSH PROGRAMMING...... 189

Using the ...... 190 How Absoft Fortran 90/95 Interfaces with the Toolbox...... 191 How Absoft Fortran 77 Interfaces with the Toolbox...... 191 Locating the Fortran 90/95 and FORTRAN 77 Interface Files ...... 192 Passing Arguments ...... 193 IMPLICIT NONE Statement...... 195 Initialization Routines Called by Pro Fortran Startup...... 195 Using MRWE and the Toolbox ...... 196 Using STRUCTUREs and RECORDs with Toolbox...... 196 Passing the Toolbox a Pointer to a Fortran Routine ...... 197 Handles ...... 199 Accessing the Quickdraw Globals...... 201 Apple Events...... 201

Macintosh Toolbox Examples ...... 206

Interfacing with Other Languages...... 206 Interfacing with C...... 207 Fortran Data Types in C...... 207 Passing Values Between C and Fortran ...... 207 Reference parameters ...... 208 Value parameters...... 209 Array Parameters...... 210 Function Results...... 210 Passing Strings to C ...... 211 Calling Fortran math routines ...... 211 Accessing COMMON blocks from C...... 212 Interfacing with Pascal ...... 212 Fortran Data Types in Pascal ...... 213 Setting up Inter-Language Calls ...... 213 Declaring Pascal routines to be called from Fortran ...... 214 Declaring Fortran routines to be called from Pascal ...... 215 Passing Values Between Pascal and Fortran...... 215 Reference parameters ...... 216 Value parameters...... 217 Function Results...... 218 Passing Strings to Pascal...... 219 Table of Contents xi

Calling Fortran math routines...... 219 Interfacing with Assembly Language...... 220 The Fortran Stack Frame...... 220 Function Results ...... 221

Resources ...... 221 Include Files ...... 222 Adding an Icon to an Application ...... 222 The SIZE(-1) Resource ...... 224 Compiling a Resource Description File...... 225

Debugging ...... 225 Compiler Options ...... 225 Linker Options...... 225 Size Resource ...... 225

Profiling...... 226 Compiler Options ...... 226 Linker Options...... 226 Size Resource ...... 226

CHAPTER 10 USING THE FX DEBUGGER ...... 227

Introduction To Fx...... 227 How To Use This Chapter...... 227

Preparing For Debugging...... 228 Compiler Options ...... 228 Linker Options...... 230 Size(-1) Resource ...... 230 Additions ...... 231 Starting A Debugging Session...... 231

Debugging Concepts...... 233 Getting Started...... 233 Single Stepping...... 234 Using Breakpoints ...... 234 Displaying Variables ...... 236 Changing Variables ...... 240 Debugging Hints...... 240

Fx Menus and Windows ...... 241 File Menu ...... 241 New Source (aN) ...... 241 Open… (aO) ...... 241 Open Workspace…...... 241 Add Path… ...... 242 Close (aW) ...... 242 Save Workspace ...... 242 Save Window Positions ...... 242 Quit (aQ)...... 242 Edit Menu...... 242 Undo (aZ)...... 243 Cut (aX)...... 243 Copy (aC) ...... 243 Paste (aV)...... 243 xii Fortran User Guide

Clear...... 243 Select All (aA)...... 243 Preferences...... 243 Environment...... 243 Format ...... 244 Startup ...... 245 Control Menu...... 246 Continue (aJ)...... 246 Kill (aK) ...... 246 Stop ...... 246 Restart ...... 246 Return (aR) ...... 246 Step Into (aI)...... 247 Step Over (aS)...... 247 Run To (aT)...... 247 Down (a [) ...... 247 Home (aH)...... 247 Up (a]) ...... 248 Clear All Breakpoints...... 248 Show Program Counter (aP)...... 248 View Menu ...... 248 Address… ...... 249 Line… ...... 249 Next (a9) ...... 249 Prev (a0)...... 249 Globals ...... 249 Locals...... 249 Statics...... 250 Types...... 250 Change… ...... 250 View As… ...... 250 Code For “”...... 250 Actions Menu...... 251 Find… (aF) ...... 251 Find Again (aG) ...... 251 Print “” (aE) ...... 251 Print * “” (aD) ...... 251 Print As… ...... 252 Watch “” ...... 252 Watch * “” ...... 252 Watch All...... 252 Watch As…...... 253 Watch Locals ...... 253 Set Breakpoint On “” ...... 253 Profile Menu ...... 253 Configure… ...... 253 On...... 253 profmt…...... 254 Windows Menu...... 254 Hide Toolbar/Show Toolbar ...... 254 Tile...... 254 Cascade ...... 254 Assembly (a1) ...... 254 Breakpoints (a2)...... 255 Classes (a3) ...... 256 Code (a4)...... 257 Memory (a5) ...... 257 Table of Contents xiii

General Registers (a6) ...... 258 FPU Registers ...... 259 Stack (a7)...... 259 Symbols (a8)...... 259

Profiling...... 260 Options For Profiling...... 260 Compiler Options...... 260 Linker Options...... 261 Profiling With Fx...... 261 Using Profmt ...... 262 File Menu...... 263 Open… (aO) ...... 263 Close (aW) ...... 263 Info (aI) ...... 263 Page Setup…...... 263 Print… (aP)...... 263 Quit (aQ)...... 264 Edit Menu ...... 264 Undo (aZ)...... 264 Cut (aX)...... 264 Copy (aC)...... 264 Paste (aV) ...... 264 Clear...... 264 Hide Time ...... 264 Hide Calls ...... 265 Hide Time/Call...... 265 Hide Graph...... 265 Sort Menu ...... 265 By Name ...... 265 By Time ...... 265 By Calls...... 265 By Time/Call...... 265 Ascending ...... 266 Descending...... 266

APPENDIX A ABSOFT COMPILER OPTION GUIDE ...... 267

Absoft Compiler Options...... 267

FORTRAN 90/95 General Options...... 267

FORTRAN 90/95 Compatibility Options...... 268

FORTRAN 90/95 Format Options...... 268

FORTRAN 90/95 Other Options ...... 269

FORTRAN 77 General Options...... 269

FORTRAN 77 Control Options ...... 270

FORTRAN 77 Compatibility Options...... 270

FORTRAN 77 Miscellaneous Options...... 270 xiv Fortran User Guide

FORTRAN 77 Format Options...... 271

FORTRAN 77 Other Options...... 272

C/C++ General Options ...... 272

C/C++ Preprocessor Options...... 273

C/C++ Format Options ...... 273

APPENDIX B LINKER ERROR MESSAGES ...... 275

Linker and MPW Error Messages...... 275

APPENDIX C ASCII TABLE...... 277

APPENDIX D BIBLIOGRAPHY ...... 281

Fortran 90/95 ...... 281

FORTRAN 77 ...... 281

C and C++ ...... 282

Macintosh Programming ...... 283

APPENDIX E TECHNICAL SUPPORT ...... 285

APPENDIX F DIFFERENCES BETWEEN PRO FORTRAN V6.2 AND V7.0 .. 287

Carbon Library ...... 287

Shared Libraries...... 287

Fortran 90 ...... 287

FORTRAN 77 ...... 287

APPENDIX G INTERFACING WITH METROWERKS CODEWARRIOR.... 289

Producing the FORTRAN object code ...... 289

Adding FORTRAN object files to a Codewarrior Projects ...... 289

Debugging FORTRAN with the Metrowerks Debugger...... 289

APPENDIX H LANGUAGE SYSTEMS FORTRAN EXTENSIONS...... 291

STRING...... 291 Table of Contents xv

POINTER...... 291

LEAVE...... 291

GLOBAL...... 291

CGLOBAL...... 292

PGLOBAL ...... 292

CEXTERNAL...... 292

PEXTERNAL ...... 292

INT1, INT2, and INT4...... 292

JSIZEOF ...... 292

%VAL, %REF, and %DESCR...... 292

Language Systems Include Files ...... 293

1

CHAPTER 1

Introduction

INTRODUCTION TO ABSOFT PRO FORTRAN Absoft specializes in the development of Fortran compilers and related tools. Full implementations of Fortran 77 and Fortran 90/95 are available for Macintosh, Windows, and Intel-based Linux platforms. Absoft will continue to focus on Fortran in the future, but the popularity of C/C++ in the Unix environment has required many of today's Fortran programmers who are moving code to their desktop, to link Fortran code with C libraries. To facilitate this process, certain Absoft Fortran implementations also include a C/C++ compiler, allowing users to create mixed Fortran/C applications from within a single development environment.

This User Guide is designed for Pro Fortran. It explains the operation of Absoft Fortran 90/95, Absoft FORTRAN 77, and Absoft C/C++. In the event you have licensed only one of these compilers, please refer only to the appropriate section(s) and disregard the others. All compilers operate in a similar manner, share a common tool set, are link compatible, and are invoked from a common user interface. A brief summary of each compiler appears below.

Absoft Fortran 90/95 A complete ANSI Fortran 90/95 implementation plus extensions. Absoft Fortran 90/95 is the result of a five year joint development effort with Cray Research. It utilizes a version of the CF90 front-end and is source compatible with several Cray F90 releases. It provides full support for the Macintosh API, the toolbox, directly from Fortran and is capable of building shared libraries. Several popular VAX and workstation extensions have also been added.

Absoft FORTRAN 77 Refined over 16 years, with emphasis on porting legacy code from workstations. Absoft Fortran 77 is full ANSI 77 with MIL-STD-1753, Cray-style POINTERs, plus most extensions from VAX FORTRAN as well as many from IBM, Sun, HP, and Cray. Absoft Fortran 77 supports legacy extensions that are not part of the Fortran 90/95 standard. See the chapter on Porting Code in this manual for further information. Fortran 77 is fully link compatible with Fortran 90/95 and C/C++ so existing, extended FORTRAN 77 routines can be easily compiled and linked with new Fortran 90/95 or C/C++ code. The entire Macintosh toolbox is supported and shared libraries can be created directly from Fortran.

Fortran User Guide 2 Introduction

Absoft C/C++ A combination of ANSI C, K&R C and C++ workstation class compilers. Absoft C/C++ is supplied to facilitate mixed Fortran/C/C++ development. The entire Macintosh toolbox is supported and shared libraries can be created from C and C++.

Absoft Pro Fortran implementations include all of the tools necessary for you to create stand-alone, double-clickable Macintosh applications. The purpose of this User Guide is to offer step-by-step instructions on the operation of each compiler, writing, compiling, debugging, linking and running your program. MRWE, Absoft's application framework can automatically build a standard Macintosh interface for each compiled application. MRWE is written entirely in Fortran and the complete source code is included as an example for Macintosh programming in Pro Fortran. Graphics routines, various libraries, and utilities are also provided. Their operation is explained in various appendices.

THE MACINTOSH PROGRAMMER'S WORKSHOP With Absoft Pro Fortran, the compiler is only part of the programming process. Editors, linkers, profilers, debuggers, etc. are all parts of the environment necessary for efficient development. Pro Fortran is designed to operate with the same high quality tools used by Apple's own engineers: tools written and maintained by Apple to provide the highest quality development environment for programmers using the Macintosh. By following the standards established by Apple, Absoft Fortran 77, Fortran 90/95, C and C++ work with Apple's C, C++, and Assembly language compilers and other third party tools.

All of this is made possible via a common programming environment: the Macintosh Programmer’s Workshop (MPW), an integrated environment that is easy on beginners and a blessing to experienced programmers. Since Absoft Pro Fortran works within MPW, a few things should be noted:

• MPW is itself an application. You can double-click on the MPW Shell icon to launch it or you can open MPW document files (FORTRAN source files) to launch MPW and use the compiler.

• There is always a Worksheet window that displays compiler messages and any errors. As you enter text into the Worksheet, the contents are automatically saved between sessions. The Worksheet should be periodically cleared, since it can grow quite large.

• The Return and Enter keys have very different meanings in the MPW environment. The Return key moves to the line while the Enter key executes MPW commands.

Fortran User Guide Introduction 3

COMPATIBILITY Absoft Pro Fortran for the PowerPC has excellent mainframe compatibility. Most popular VAX/VMS statement extensions are accepted as well as several from IBM/VS, Cray, Sun FORTRAN and the new Fortran 90/95 standard. In addition, Absoft Pro Fortran for PowerPC is 100% source-compatible with other Absoft compilers for Macintosh, Windows 95/98, Windows NT, and Intel-based Linux workstations. See the chapter Porting Code for additional compatibility information.

CONVENTIONS USED IN THIS MANUAL There are a few typographic and syntactic conventions used throughout this manual for clarity.

• [] square brackets indicate that a syntactic item is optional.

• … indicates a repetition of a syntactic element.

• Term definitions are underlined.

• -option font indicates a compiler option.

• Italics are used for emphasis and book titles.

• On-screen text such as menu titles and button names look the same as in pictures and on the screen (e.g. the File menu).

• The modifier keys on Macintosh keyboards are Shift, Option, Command, and Control. They are always used with other keys and are referenced as in the following:

Option-W (hold the and press W) Command-period (hold the and press '.') a-. (same, a is the Command key symbol)

• Unless otherwise indicated, all numbers are in decimal form.

• FORTRAN examples appear in the following form:

PROGRAM SAMPLE WRITE(9,*) "Hello World!" END

ROAD MAPS Although this manual contains all the information needed to write programs with Absoft Pro Fortran on the Macintosh, there are a number of other manuals that describe Fortran

Fortran User Guide 4 Introduction

90/95, FORTRAN 77, and C/C++ extensions; the Macintosh Programmer's Workshop (MPW) and the Macintosh toolbox; and Macintosh programming in further detail. The two road maps in this chapter will guide you to these manuals for introductory or advanced reference. The bibliography in appendices lists further information about each manual.

Fortran Road Maps The Absoft implementation of Fortran 90/95 is detailed in the online manual, Fortran 90 Concise Reference, in the Documentation folder of the Pro Fortran CDROM. FORTRAN 77 is detailed in the online manual, FORTRAN 77 Language Reference Manual, also in the Documentation folder of the Pro Fortran CDROM. A discussion of floating point precision is at the end of the chapter Porting Code. Figures 1-1 shows additional manuals that can be used for referencing the FORTRAN language and internal math operations.

Absoft Fortran User Guide

ANSI FORTRAN 77 Standard IEEE Floating Point Standard ANSI X3.9-1978 P754

ANSI Fortran 90 Standard Inside Macintosh: RISC Numerics ANSI X3.198-1992 Apple Computer, Inc

ANSI C Standard Apple Numerics Manual ANSI X3.159-1989 (SANE)

Annotated C++ Reference Manual Ellis and Stroustrup

FORTRAN 77 language road map Figure 1-2

Macintosh Programming Road Map Absoft Pro Fortran provides complete access to the Macintosh toolbox routines, both in the traditional or ‘Classic’ interface as well as the new ‘Carbon’ interface. This manual describes the interface to these routines, but does not describe each of the thousands of

Fortran User Guide Introduction 5

routines available. Programmers wishing to make use of these routines to add graphics to their programs or to extend the user interface provided by MRWE, may wish to purchase additional documentation on the Macintosh toolbox. Figure 1-3 lists the documentation produced by Apple.

Figure 1-2 is divided into three sections for different levels of Macintosh familiarity. The first shows the books that introduce the Macintosh User Interface and general Macintosh programming concepts to Fortran programmers new to the Macintosh. The second section is the most likely starting place for Fortran programmers familiar with using Macintosh applications. The last section is for programmers using languages such as C, Pascal, or assembly in conjunction with Absoft Pro Fortran.

Fortran User Guide 6 Introduction

Programmers new to Technical Introduction to the the Macintosh Macintosh Family

Human Interface Guidelines: The Apple Desktop Interface

Programmer's Introduction to

the Macintosh Family



Programmers familiar Absoft Fortran 77/90 Inside Macintosh Volumes I-VI with Macintosh Language Reference Manuals concepts

Inside Macintosh: Risc System Software

Macintosh Technical Notes



Programmers using Macintosh Programmer's multiple languages Workshop (MPW) Reference

MPW C & Pascal Reference MPW Assembler Reference Manuals

Macintosh programming road map Figure 1-2

Fortran User Guide Introduction 7

YEAR 2000 PROBLEM All versions of Absoft Pro Fortran products for Macintosh, Power Macintosh, Windows 95/98, Windows NT, Linux, and UNIX will operate correctly across the date transition to the year 2000. Neither the compilers nor the runtime libraries have ever used 2-digit years in their internal operation. This means the version of Absoft Pro Fortran that you already have will continue to operate correctly. No patches or version updates are required.

The only caveat may be for those porting code from VAX/VMS systems. Since the early 1980s, Absoft Pro Fortran products have included software libraries designed to facilitate porting code from the VAX/VMS environment. Included in these VAX compatibility libraries are two subroutines that emulate the VAX/VMS DATE and IDATE subroutines. These subroutines return the year using a two-digit format. If you use DATE or IDATE in a program that stores or compares dates, you may need to recode portions of your application. Below are listed some of the alternatives supplied with Pro Fortran:

Fortran 90/95 DATE_AND_TIME Subroutine This subroutine is part of the Fortran 90/95 language and returns integer data from the date and real time clock. Refer to the Fortran 90 Concise Reference for further information.

Unix Compatibility Library There are a number of subroutines in the Unix Compatibility Library that return the date and time in both INTEGER and CHARACTER format. Refer to the section Absoft Compatibility Libraries at the end of the FORTRAN 77 Language Reference Manual for information on their format and use.

Fortran User Guide

9

CHAPTER 2

Getting Started

This chapter introduces the three main components of the Absoft Pro Fortran package — editing files, compiling source code, and using compiled applications.

MPW conforms to the Macintosh User Interface, so you need to be familiar with basic Macintosh skills, such as using menus and selecting with the mouse. Also, you should be familiar with using windows, pop-up menus, dialog boxes and alert boxes. For more information, consult the Macintosh Reference manual.

If you are familiar with MPW and would like to skip this chapter, use the table below to locate other areas of interest.

TO DO THIS… TURN TO THIS SECTION… Use the compiler Using the Compiler, Chapter 5

Create applications Building Programs, Chapter 7

Program the Macintosh Macintosh Programming, Chapter 9

Edit source files Editing Files, Chapter 3

Debugging Fortran programs Using the Fx Debugger, Chapter 10

Topic guide for experienced MPW users Table 2-1

INTRODUCTION TO MPW AND ABSOFT PRO FORTRAN Absoft Pro Fortran is used within the Macintosh Programmer's Workshop (MPW). MPW provides a powerful programming environment for programmers, including an integrated, window-based text-editing environment for the Absoft Pro Fortran compilers and extensive file manipulation capabilities. In addition to its many built-in commands, MPW also includes a command interpreter and a set of programming tools.

STARTING AN MPW SESSION There are two ways to start an MPW session: double-click on the MPW Shell icon in the MPW folder or double-click on any MPW document file. As you create and edit FORTRAN source files within MPW, you save them as MPW documents.

Fortran User Guide 10 Getting Started

MPW icons Figure 2-1

In the following example, we'll open MPW by double-clicking on the MPW Shell.

What to do How to do it Start MPW by opening the Double-click on the MPW MPW shell icon. shell icon in the MPW folder.

THE MPW ENVIRONMENT The first window to appear when you begin a session in MPW is the Worksheet window. While MPW loads, you may notice a box with words flashing under the title bar: this is the Status Panel. When the MPW shell is not executing, the Status Panel displays the words “MPW Shell.” At the top of the Worksheet window is the Title Bar that shows the directory of the Worksheet.

MPW environment Figure 2-2

Source files may be created, edited and compiled from within MPW using its command language. To initiate a command from within MPW, use the menus or enter a command line in an MPW window.

Fortran User Guide Getting Started 11

Using the Menus The menu bar is located at the top of the screen. MPW menus are the easiest way to execute a command— simply select the command from the menu. The Tools menu is used to start the Absoft Pro Fortran compilers; other menus invoke commands for working with source files, and specifying directories.

The MPW Editor, the set of editing commands in MPW, provides extensive capabilities to create and edit source files. A text window can be accessed to enter and edit files in the same way that you would use a word processor. The MPW Editor is customized for programming tasks and provides a better alternative to using a generic word processor. When using MPW remember that there are no separate typing and editing modes. Simply enter your text and separate lines of text with the Return key. If you want to edit your text, select a command from the menus.

Using the Worksheet The Worksheet window is always open and accessible during an MPW session. Since it cannot be closed, you can use the Worksheet like a console to type in all of your commands and see the output. MPW commands can be initiated from any text window however, the Worksheet is more useful for executing command lines.

By default, MPW command output is sent to the window where the command was executed. For instance, the Help command sends information to the window, information you usually do not want to include in your text files. If you execute the Help command in the Worksheet window, the help information is sent to the Worksheet window without affecting the contents of a text window.

To execute an MPW command from the Worksheet, type in the name of the command and press Enter. You can also use the Status Panel to execute a command: a mouse click on the Status Panel is equivalent to pressing the Enter key. MPW commands are discussed in the chapter Using the Worksheet; the entire MPW command language is described in the MPW Reference Manual.

Executing Commands from the Worksheet This next example shows how easy it is to execute a command from the Worksheet window. To initiate the Help command from the Worksheet, type Help followed by the command or tool name and press Enter. For example, if you wanted a description of the files command:

What to do How to do it

Show help for the Fortran Type help files on a new compiler, the files tool. line in the Worksheet and press Enter.

Fortran User Guide 12 Getting Started

Help Example Figure 2-3

If you need general information on available Help topics, type Help and press the Enter key.

The Commando Interface Every MPW command has an easy-to-use Commando interface. When you choose a command from the menus, the dialog box that you see is a part of the Commando interface. This interface can also be accessed through a command line from the Worksheet. The Commando interface is helpful when you need to execute a command with multiple options and parameters. With the commando interface, you do not need to remember all of the options for MPW commands. The Commando interface allows you to build MPW commands lines directly from dialog boxes with help information readily available.

The Commando dialog for any command can be invoked from the Worksheet by typing the command name and pressing Option-Enter. The Commando interface is covered in more detail in chapter Using the Worksheet.

Fortran User Guide Getting Started 13

WORKING WITH SOURCE FILES Now that you have started up MPW and looked briefly at the MPW environment, we will open an MPW document named Hello.f90 in the FExamples folder.

What to do How to do it

Open the document using the Choose the File menu and Open command. select the Open command.

Locate the Examples folder Double-click on the Examples within the MPW folder and folder, then double-click on open the FExamples folder. the FExamples folder.

Open the example source file Double-click on Hello.f90. Hello.f90 in a window.

The Hello.f90 source file will appear in a window, ready for editing.

The Hello.f90 source file Figure 2-4

Fortran User Guide 14 Getting Started

Editing Text We can get a feel for using the editing environment of MPW by making a small change to the Hello.f90 source code.

What to do How to do it Change the message text in Select the text, as shown in the Hello.f90 example to Figure 2-5, and type the new something different such as message (don’t type a second “Three hellos”. set of quotations).

Selecting text Figure 2-5

Now, save the changes to your file using the Save command.

What to do How to do it

Save the changes to the Pull down the File menu and Hello.f90 file on disk. select the Save command.

Fortran User Guide Getting Started 15

COMPILING CODE

The Hello.f90 file is ready to be compiled by Absoft Pro Fortran. The compiler is accessible through the Tools menu at the right end of the menu bar. When compiled and launched (from the Tools menu), this small Fortran 90/95 program will display a message and then wait for the Return key to be pressed.

What to do How to do it

Display the dialog box for the Pull down the Tools menu compiler. and select the Compile and Launch… command.

Select the source file, Click on the Source File(s)… Hello.f90, to compile. button to display a file selector for building a list of files to compile.

Select the Hello.f90 file and press the Add button to include it in the list.

Press the Done button since Hello.f90 is the only file to compile.

Compile the file to generate Press the Compile button. The an application. application is given the default name Link.Out.

Fortran User Guide 16 Getting Started

Compiling Hello.f90 Figure 2-6

If the Hello program does not launch and a message such as:

### MPW Shell - Could not launch Link.Out is displayed in the Worksheet window, there is not enough memory to launch the program. Absoft Pro Fortran requires as little as two megabytes of memory but the System or other applications can use large amounts of memory.

In this tutorial, the application is automatically launched when the Compile and Launch… command is selected in the Tools menu. When compiling code, the Absoft Fortran 90/95 compiler creates an application, Link.Out that may be modified with options. See the chapter Using the Compiler for more information.

APPLICATION BASICS Every application created by Absoft Pro Fortran has the same look and feel of all other Macintosh applications. This environment, called the Macintosh Runtime Window Environment (MRWE), makes it easy to compile and run Fortran programs created on the Macintosh and other computers. Figure 2-7 shows the Hello.f90 application as it will look when it is run.

Fortran User Guide Getting Started 17

The look of a running application Figure 2-7

Any text in the window, such as the message displayed, may be selected and copied to the Clipboard for pasting into other applications. Furthermore, the File menu has commands for saving and printing text in the window.

Also, any MRWE applications are built with the Macintosh Carbon library, enabling them to be moved to the Macintosh OS X environment and execute with the look and feel of that .

To close the MRWE output window and quit from your new application, press Return two times. The Hello.f90 application window will close and return you to the MPW worksheet. The first Return satisfies the read(*,*) in the Fortran source code(hello.f90) and the second Return closes the MRWE output window.

What to do How to do it

Quit the Hello application. Use the mouse to pull down the File menu and select the Quit command.

Fortran User Guide 18 Getting Started

ENDING AN MPW SESSION

Any text in the Worksheet is automatically saved when you quit MPW. The text in the Worksheet window can be saved to a text file, or it can be deleted at any time by highlighting it and pressing the Delete key.

What to do How to do it Save the Worksheet contents Use the mouse to pull down to a separate file. the File menu and select the Save a Copy command. In the dialog, type a name for the file and click OK.

To quit from MPW, use the File menu.

What to do How to do it Quit MPW. Use the mouse to pull down the File menu and select the Quit command.

Fortran User Guide 19

CHAPTER 3

Using the Editor

One of the most powerful features of MPW is its editing capabilities. From the editor, you can edit multiple files or search for text patterns. Fortran source files and any other text-only files (type TEXT) can be edited and manipulated with the commands explained in this chapter.

THE MPW EDITOR The MPW editor allows you to create and edit source files written in Fortran. Since word processors embed formatting characters in a document, using a word processor to create source files is not recommended. You can create source files in a word processor or another editor and export them to the MPW Editor in text format, but the features of the MPW editor make this unnecessary. The editor is easy to work with and all MPW and Absoft Fortran 90/95 commands are accessible to you at all times.

Basic editing functions in MPW are available as menu commands: most of these menu functions are also duplicated in the MPW command language, covered in the chapter Using the Worksheet. Since the command language is integrated throughout the MPW environment, there is usually more than one way to initiate any command:

• Select the command from the menu, or,

• Type in the Command-key equivalent (such as typing the command key and the letter O (aO) for the Open command.)

• Type the command name in a window and press Enter.

This chapter specifically covers the editing commands in the menus and their Command- key equivalents.

CREATING FORTRAN SOURCE FILES

To create a new source file, choose the New command from the File menu. A standard selection box will ask you to name the new file. After you have created the file, by clicking the New button, text can be entered and edited using the same editing techniques you use with a Macintosh-based word processor. You can cut and paste lines of text within the window, and move the cursor to enter text at any line.

Fortran User Guide 20 Using the Editor

Dialog for creating a new text file Figure 3-1

Text window Figure 3-2

Here are some basic things to remember when creating text files in MPW:

1. Always use the Return key to end a line rather than the Enter key. The Enter key tells MPW to execute a line of text as an MPW command. There is no separation of editing and command modes in MPW; it distinguishes between the two modes only when you execute a string of text with the Enter key.

Fortran User Guide Using the Editor 21

2. Standard mouse techniques for highlighting text can be used while editing a file. Clicking and dragging the cursor over multiple text lines in a window will highlight the lines. A double-click on a word will highlight the word. Triple-clicking selects an entire line.

Manipulating Windows One or more text windows can be open at any time in MPW, allowing you to cut and paste text between files. Text windows have a Title Bar, a Status Panel, and vertical and horizontal Scroll Bars. At the top/left of the scroll bar, a black rectangle called a Split Bar can be dragged to create windowpanes within one window. When a pane is created, a box called the Slide box will appear at the end of the Scroll Bar. Use the Slide Box, the box with direction arrows, to resize the pane.

When working with multiple windows, it is important to note that MPW distinguishes between the active window (the frontmost window) and the target window (the second window from the top). Most of the editing commands initiated from the menus will affect or insert text in the active window. If you want to know which window is your active window, check the Window menu. In the Window menu, the active window will have a check mark (9) next to it. The target window, which is explained in the chapter Using the Worksheet, has a bullet (•) next to it. Any open window that has any unsaved changes will be underlined.

USING THE EDITOR MENUS

The rest of this chapter covers the shell editor commands in the File, Edit, Find, Mark, Window and Directory menus. The name of the command is given, followed by its Command-key equivalent and a description of its function.

MPW also allows you to create and edit menus with the AddMenu command covered in the chapter Using the Worksheet. Commands may be added to menus, or you can create new menus. In fact, the Tools menu was created using the AddMenu command.

File Menu The File menu contains commands for opening, closing, saving, and printing files.

New…(aN) Creates a new text file such as a Fortran source file. When you select New from the File menu, it displays a standard file dialog box for entering a file name. After entering a name for the file, a new text file is created.

Fortran User Guide 22 Using the Editor

Open…(aO) Opens an existing text file in a window for editing. This command displays a standard file box for you to select a file to be opened. If you select a file that is already open, the window that contains the document is brought to the front.

Open Selection (aD)

This command is similar to Open, except that this command opens the currently selected text in the frontmost window. This command is handy for opening Fortran INCLUDE files. To open an INCLUDE file or other document named in the window: • Highlight the name of the file in the window. (To open an INCLUDE file, select the name in the source code after the INCLUDE statement).

• Select Open Selection from the File menu, or, press aD (the Command-key equivalent for Open Selection).

Selection of INCLUDE file name for opening Figure 3-4

Close (aW)

This command closes the front-most window. If any unsaved changes had been made to the text, you will be asked to save it. Since the Worksheet window cannot be closed, this command will not apply to this window. When you quit from MPW, the Worksheet is automatically saved.

Save (aS)

Choose this command to save the text in the front-most window. The first time you save, you will need to name the file and tell MPW where you want the document to be stored. After this, each time you save the document, the current version is saved to this file. If no changes have been made in the window this command is dimmed and unavailable.

Save as…

Fortran User Guide Using the Editor 23

Use this command to save the text of the front-most window to a different file. A standard Save As dialog box is displayed allowing you to enter a new file name and specify any folder or volume. The front-most window becomes the newly named file.

Save a Copy…

This command is similar to Save as… except, after saving to a new file, the old file is still in the front-most window, ready to be edited. Use this command to save the contents of the Worksheet to a text file. Revert to Saved

Ignores all changes made since the front-most window was last saved.

Page Setup…

Use this command to display the standard Page Setup dialog box for printing.

Print Window

This command prints the contents of the front-most window to the current printer. To select or change the current printer, use the Chooser in the . The Print Window menu command does not show the usual dialog box: it only alerts the user that the document is printing. To change printing defaults (such as page numbers, headers and footers) you will need to invoke the print command from the Worksheet window (see the chapter Using the Worksheet for more information).

Quit (aQ)

Quit exits MPW and returns you to the Finder. If you have any unsaved changes in any window, you will be asked to save them. The Worksheet window is automatically saved when quitting. However, this default can be modified; customizing the Worksheet is discussed in the chapter Using the Worksheet.

Edit Menu The Edit menu contains the standard editing commands for cutting, pasting, and copying text. Commands designed specifically for programmers are also located at the bottom of the menu.

Undo (aZ)

Use this command to undo the last change made in the front-most window. Choosing Undo a second time puts the changes back.

Cut (aX)

Fortran User Guide 24 Using the Editor

This command removes the selected text in the front-most window and places it on the Clipboard. Text on the Clipboard may be pasted into other windows.

Copy (aC)

The Copy command duplicates the selected text from the front-most window onto the Clipboard and leaves the text in the window unchanged. Text on the Clipboard may be pasted into other windows.

Paste (aV)

This command replaces the selected text of the front-most window with the text on the Clipboard. If no text is selected in the front-most window, the Clipboard text is inserted at the insertion point.

Clear

Similar to Cut, this command removes the selected text from the front-most window but does not place a copy on the Clipboard. The Clipboard remains unchanged.

Select All (aA)

Use this command to select all of the text in the frontmost window.

Show Clipboard

This command displays the contents of the Clipboard in a separate window.

Format… (aY)

This command is used to change the font and font size of the text in the front-most win- dow. The default font is 9-point Monaco. Changes will stay in effect even after the file is closed. The dialog shown in Figure 3-5 shows additional settings that may be changed.

Format command dialog box Figure 3-5

Fortran User Guide Using the Editor 25

The Auto Indent check box automatically indents the next line with the same spacing as the current one. Option-Return may be used at the end of a line to override the indentation.

The Show Invisibles check box displays spaces and control characters in the window. The following symbols are displayed within the text in the window:

∆ Tab

◊ Space

¬ Return

¿ Control characters

The Tabs field defines the number of spaces a tab character is expanded to in the file. To change the tab spacing, type the desired number in the Tabs text field. Be cautious when changing tab sizes: Fortran 90/95 source in fixed format is dependent upon column positions. The limit for the tab field is 100 characters. A recommended number for Fortran programs is 6 characters.

Align

This command is used to horizontally align the selected text with the top line of the selection.

Shift Left and Shift Right (a [ and a])

Use these commands to horizontally shift a block of selected text by one tab stop, either to the left or to the right. Shift Right is ideal for indenting a block of code, such as the lines of a DO loop. By holding down the Shift key while choosing these commands, the text will shift by a single space rather than by a tab character.

Find Menu The Find menu contains commands for searching and replacing text.

Find… (aF)

This command is used to search for text, text patterns, or line numbers.

Searching for Line Numbers

To find a line number, click on Selection Expression, type in the line number in the text box and click on the Find button. The command will search the text beginning at the current selection or insertion point.

Fortran User Guide 26 Using the Editor

Find command dialog box Figure 3-6

Searching for Text

There are three general options to search for text:

Literal finds the exact string regardless of any characters surrounding it in the window.

Entire Word finds the string only when the characters before and after it are not word characters: a-z, A-Z, 0-9; or when characters are not underscored.

Selection Expression interprets the entered text as a regular expression and matches the text as a pattern.

In addition to these general options for finding text, the following options add more flexibility and control to the text and pattern searches described above:

The Case Sensitive check box, when selected, will control whether the three searching options should match upper or lower case characters. By default, the find command is case insensitive.

Select the Search Backwards check box to search for text toward the beginning of the file. The search for text stops at the end of file with forward searches; it stops at the beginning of a file for backward searches. This box is only available for Literal and Entire Word searching.

When the Wrap-Around Search check box is clicked, searching continues until reaching the start of the search. This box is only available for Literal and Entire Word searching.

When using Selection Expression to search for text in specific patterns, different symbols can be used as wildcard characters to match repeating or unknown characters in expressions. This table shows the special characters that may be used in regular expressions:

Fortran User Guide Using the Editor 27

? Matches any single character.

≈ Matches any string of zero or more characters not including Return. The ≈ character is entered by typing Option-X.

[characters] Any character in the list is matched. The brackets contain the list and must be present.

[¬characters] Any character not in the list is matched. The brackets contain the list and must be present. Type the ¬ character with Option- L.

These special characters along with the text must be between slashes (// for forward searches or \\ for backward searches). Figure 3-7 is an example that finds any string beginning with the characters “DO”.

Find dialog election expression Figure 3-7

Find Same (aG)

This command repeats the last Find command in the front-most window. This command has the Command key equivalent aG. To reverse the direction of the search, hold down the Shift key while typing aG. If you hold down the Shift key when you click OK, the Find command will reverse the direction as well.

Find Selection (aH)

Use this command to find the next occurrence of the selected text in the front-most win- dow. For example, selecting the name of a variable in the declaration section and pressing aH, the Command key equivalent for this command will search for the first use of the variable.

Display Selection

Ensures the current selection or insertion point is visible in the front-most window.

Fortran User Guide 28 Using the Editor

Replace… (aR)

This command is used to find and replace text. It displays a dialog box similar to that for the Find command with a few additions.

Replace dialog box Figure 3-8

The Replace button searches for the top string and changes the first occurrence, if found, to the bottom string. The Replace All button does the same but for all occurrences in the file.

Replace Same (aT)

Use this menu command to repeat the last Replace command.

Next Error (a≥)

Use this menu command to locate the source line containing the next error or a warning. See Errors While Compiling in the chapter Using the Compiler for information on how the compiler reports errors and warnings and how you can use this diagnostic output to quickly locate problem lines in your source files.

Previous Error (a≤)

This menu command will locate the previous source line containing an error or a warning.

Mark Menu The Mark menu allows you to set markers within text files. A marker is a section of text that has been previously named, and is used to locate and navigate through these sections of text. With the Mark… command, you can set markers at the insertion point within a text window. The Mark menu also contains commands for removing markers and finding marked sections of text in other files. As markers are created, they are listed as menu commands in the lower part of the Mark menu. To move to a specific portion of text, select the corresponding marker.

Fortran User Guide Using the Editor 29

Mark… (aM)

This command adds a new marker to the list in the Mark menu. To add a marker, either select a section text, or place the insertion point at the beginning of a section of text. Choose the Mark… command and type a name for the marker in the dialog box.

Marker dialog box Figure 3-9

Click the OK button. This name will appear in the lower part of the Mark menu. If you type the name of an existing marker, a dialog box will appear and give you the chance to either delete the old and add the new one, or Cancel.

Unmark…

To remove a marker from the Mark menu, choose Unmark and select the marker name from the list of markers in the dialog box.

Unmark dialog box Figure 3-10

If you click Delete, every marker that you have selected will be deleted. If you cancel, the selection is unchanged.

Browse…

The Browse command provides a fast way to find a marker in any file. When selected, a dialog box appears containing a list of files and folders. As you select a file, any markers in the file will appear on the right side of the dialog. To view that marker, double-click on the marker name. This opens the file with the marked text selected.

Fortran User Guide 30 Using the Editor

Browser dialog box Figure 3-11

Alphabetical

List the markers in the bottom half of the Mark menu alphabetically.

Window Menu The Window menu contains two commands for positioning windows: Tile Windows and Stack Windows. This menu lists all open windows in the order in which they were opened. By choosing a window from the list, that window is brought to the front. A checkmark (9) next to a window in the list indicates the active window (front-most window). A bullet (•) next to a window indicates the target window, the second window from the front. If the window name is underlined, this indicates that the contents of the window have changed since the last save. Tile Windows This command arranges all text windows in a tiled pattern, thus preventing any overlap. The Worksheet window is not affected by this command. Hold the Option key while choosing this command to tile the Worksheet.

Stack Windows

This command arranges all text windows in an overlapping stacked pattern. The Worksheet window is not affected by this command. To stack the Worksheet with the text windows, hold the Option key.

Directory Menu The Directory menu allows you to display or change the default or current directory. The default or current directory determines how an MPW command operates from the Worksheet.

Fortran User Guide Using the Editor 31

When you start MPW, the default or current directory is set to the location where MPW was launched. If you wish to invoke a command from the Worksheet that accesses a file in another directory, you must specify the entire pathname or the command will result in an error. The commands in the Directory menu are used to set the default or current directory for commands executed from the MPW Worksheet.

As you change the default or current directory with the Set Directory command, each new directory is added as a separate menu item at the bottom of the menu to allow you to easily reselect it at any time.

Show Directory

This command shows an alert box with the name of the current directory.

Set Directory...

A dialog box appears, allowing you to select the directory where files will be saved. After you click OK, the selected directory will be shown at the bottom of the menu. To choose a directory, select a folder and click the Directory button.

Set Directory dialog box Figure 3-12

Fortran User Guide

33

CHAPTER 4

Using the Worksheet

This chapter will provide you with the information necessary to use the MPW Worksheet to initiate MPW commands, access on-line help in MPW, and execute programs and tools created by Absoft Pro Fortran. If you desire more information, refer to the Macintosh Programmer's Workshop Manual listed in the bibliography appendix.

THE WORKSHEET WINDOW Commands drive the MPW environment. To tell the MPW shell to perform a specific operation, commands are issued using the menus or by typing the equivalent command line in a window. The menu commands covered in the Using the Editor chapter make it easy to edit source files and execute commands. These editing commands are a part of MPW's command language set, which also includes many other useful commands for customizing the MPW environment, working with Fortran programs, or managing source files.

Commands can be executed in any text window; however, the MPW Worksheet provides a short-cut to executing commands in MPW. Within the Worksheet window, any commands can be entered and sent directly to the command interpreter for execution. When you use the Worksheet to execute commands, you can keep track of all commands initiated during a session.

Fortran User Guide 34 Using the Worksheet

The Worksheet window Figure 4-1

The Worksheet window is the main work area of the MPW environment and is the first window that opens when you begin an MPW session. The Worksheet window cannot be closed and is always accessible. When you quit MPW, the Worksheet automatically saves its contents. You can delete the contents of the Worksheet at any time or save the text in the Worksheet to a new file using the Save a Copy command in the File menu.

Executing commands from the Worksheet also helps you to determine where command output will appear. By default, command output is sent to the window where the command line was executed. By invoking commands from the Worksheet, you are assured that any output will appear only in the Worksheet and not in any text windows. For information on directing command output to other text windows, see the section Routing Command Output later in this chapter.

MPW COMMANDS MPW commands can be divided into four categories:

1. Shell commands initiate the commands that are a part of the MPW shell. For instance, the editing commands in the menus are examples of shell commands.

Fortran User Guide Using the Worksheet 35

2. Tools commands execute tools, the separate programs that are integrated within the MPW environment. Each MPW tool has a corresponding MPW command name. Sometimes the terms MPW commands and MPW tools are used interchangeably, but there is an important difference. An MPW tool is not equivalent to a built-in command; it is a separate program that performs more complex tasks. Some examples of the tools in MPW are the actual Fortran 90/95 compiler, the linker, and the resource tools, Rez and DeRez.

3. Script commands execute script files. Scripts are text files containing lists of commands. Any series of commands can be combined and saved into a command file. The script command name is the name of the file: to execute a script, type the filename as you would any other command. Scripts will be explained later in this chapter.

4. Outside applications, such as MacDraw II or MacPaint, can also be launched within the MPW environment as a command. Any program can be launched from the Worksheet by entering its name.

Command Syntax Every command line executed in MPW follows a specific guideline for its syntax:

Commandname [parameter...] terminator

The commandname is the main keyword of the command; it tells the shell to perform a specific operation. Each command can be modified by any combination of parameters—an option or a filename. Options direct the command; they specify how the command should work or what the output should look like.

Every command line also has a terminator, a symbol that tells MPW to end the operation associated with the command. The most common way to terminate a command is to use the Return key, which adds the end of line terminator. Remember that the Return key will not invoke a command—it only ends a command line.

Executing MPW Commands from the Worksheet To execute a command, select a command line and press Enter. If no text is selected, the command can be executed by placing the insertion point within the line and pressing Enter. Command-Return is equivalent to pressing Enter. Another way to execute a command line is to use the Status Box. A click on the Status Box is equivalent to pressing the Enter key. For instance, if you wanted to show a list of files in the current directory in the Worksheet:

Fortran User Guide 36 Using the Worksheet

What to do How to do it

Execute the Files command Type Files on a new line in which lists all the files in the the Worksheet window. current folder. Press the Enter key (not the Return key).

The list of files appears in the Worksheet, the window where you executed the command. If you want to save the list, use the File menu to select Save a Copy. Any text in the Worksheet can be deleted by highlighting it and pressing the Delete key.

Command Parameters Parameters, such as options or filenames, can be appended to MPW commands to modify or direct the command. The Files command can be used as an example. If you want to see a list of files in your current directory and include the type, size, creator, modification date and creation date, you would enter the Files command with its option to list files in long format, the letter 'l' with a dash in front (-l):

What to do How to do it

Execute the Files command Type Files -l on a new line with the option for long in the Worksheet window. format output. Press the Enter key.

A list of options for some MPW commands is given later in this chapter. For a full list of command options, refer to the MPW Command Reference Manual, available from Absoft and APDA, or type help, the name of the command, and press Enter to list the options. MPW commands are not case-sensitive: if you were to enter Files, files, or FILES, the MPW shell will interpret these in the same manner. (In this manual, the first letter will be capitalized for consistency.) To stop command execution, type the Command key and a period (Command-.).

Fortran User Guide Using the Worksheet 37

Command Terminators A command line may be executed without a terminator. When executing more than one command line, a Return character usually terminates each line. Other characters may also terminate command lines. The table below lists the other command terminator characters.

Terminator Symbol Description

command line | command line The pipe symbol saves the results of the first command and uses it as input for the second command.

command line && command The second command will be line executed only if the first command succeeds.

command line | | command line The second command will be executed only if the first command fails.

command line ; command line The first command is executed, followed by the second command.

MPW comments can also be added to command lines using a special character. The number sign (#) indicates to the shell to ignore all the text between the (#) and the Return character. MPW comments can only be terminated by a Return character.

Another useful symbol is the ∂ symbol. When followed immediately by a return, this symbol continues the command line to the next line, as shown below. To type the ∂ symbol, use Option-D.

Echo This line will not ∂ [Return] break in the window [Return]

To execute the command lines, highlight both lines and press Enter. The output will look like this:

This line will not break in the window If you enter the first line only, the Shell will pause and wait for the rest of the line.

Fortran User Guide 38 Using the Worksheet

Accessing the Commando Interface When entering long command lines in the Worksheet window, you might miss the ease of using the dialog boxes to select command parameters. The Commando interface provides interactive mouse access to all of MPW’s features and options by invoking dialog boxes for any command. The Commando interface lets you operate more intuitively with commands: all options are shown and help text can instantly be displayed. There are three ways to invoke the Commando interface for any command entered into the Worksheet:

• Press Option-Enter after typing the command.

• Type an ellipsis (…), using Option-; (Option-semicolon), after the com- mand and press Enter (i.e. Files…).

• Type Commando followed by the command and press Enter (i.e. Commando Files).

All of these methods will invoke the Commando dialog for the Files command as shown in Figure 4-2.

Commando dialog for the Files command Figure 4-2

The default button encircled with a double border in the lower-right corner of a Commando dialog executes the command, along with any options and arguments you choose. This button is referred to as the "Do It" button. As you select multiple options and files in the dialog box, the equivalent command line will appear in the Command Line Text Box.

To copy and paste the command line into a window without executing it, highlight the text in the Command Line Text Box and choose Copy from the Edit menu. The Cancel button exits from the dialog without executing the command. The command line can now be pasted into any window.

Fortran User Guide Using the Worksheet 39

To copy the equivalent command line to a window for later reference and execute it, hold down the Option key while clicking the "Do It" button. The complete command line is copied to the window where the dialog box was invoked and the command is executed.

Target and Active Windows

Window menu Figure 4-3

When you enter and execute an editing command in the Worksheet window, the command will affect the target window, the second window from the top. If you initiate an editing command from a menu, it will affect the active window, the frontmost window. If you initiate an editing command from a script, it will affect the target window. In the Window menu, the active window will have a check mark (9) next to it. The target window has a bullet (•) next to it. Any open window that has any unsaved changes will be underlined.

Routing Command Output There are two types of output for any command: standard output and diagnostic output. Standard output refers to normal output, such as a listing from the example of the Files command used earlier. Diagnostic output consists of errors and warnings that are not expected.

MPW commands do not need to be executed from the Worksheet, they can be executed from any text window. However, when a command is executed from a text window, the output appears in that window, not in the Worksheet. You can specifically name an output window as a command parameter if this creates a problem.

Occasionally, you might need to route command output to the Worksheet or another file, or even dispose of the output entirely. To route command output, add a redirection character followed by the file name that will receive the output. For example, to send the standard output of the Files command to the file CurrentListing, enter

Files > CurrentListing

Fortran User Guide 40 Using the Worksheet

Table 4-1 lists the available redirection characters.

Character Meaning (nothing) Output appears in the window in which the command was exe- cuted. > file Standard output is routed to file. >> file Standard output is appended to file. ≥ file Diagnostic output is routed to file. ≥≥ file Diagnostic output is appended to file. Σ file Standard and diagnostic output are routed to file. ΣΣ file Standard and diagnostic output are appended to file.

MPW command redirection characters (Type the ≥ character with Option-> and the Σ character with Option-W) Table 4-1

Table 4-2 contains a list of common file names to which output can be redirected.

File name Meaning

file Can be any file name. {Worksheet} Output goes to the Worksheet. Dev:Null Output is thrown away. This is the null device. Dev:StdErr Output is sent to diagnostic output.

Common MPW file names for redirected output Table 4-2

A typical use for redirecting diagnostic output is to ignore harmless errors that might occur. For example, the following command line will eject the disk in drive 1.

Eject 1 ≥ Dev:Null Since the file name specified is the null device, it will not show any errors if the drive is empty. The error message will be discarded.

Most of the sample Fortran code included with Absoft Fortran 90/95 contains comment lines near the top of the file that contain the commands, with redirection characters, necessary to compile the file. This is an excerpt from Sample.f90:

C f90 -o Sample Sample.f90 Σ "{Worksheet}"

In this example, the Σ character sends the standard and diagnostic output to the window listed (the Worksheet) instead of sending the output to the current window (Sample.f90).

Fortran User Guide Using the Worksheet 41

File Name Generation Often, you will need to generate a listing of files that you have created, either to keep track of files, or to compile source files. MPW has special characters, that when combined with a command, will allow you to search for and list certain patterns of filenames. Any unquoted word that contains the characters in Table 4-3 is considered a filename pattern.

Character Type in Meaning

≈ Option-X Matches any string of zero or more characters.

? ? Matches any single character. [list] --- Matches any character in the list.

[¬ list] Option-L Matches any character not in the list.

File name wildcard characters Table 4-3

When the Enter key is pressed, the unquoted word is replaced with a sorted list of existing filenames that match the pattern. Pattern matching is not case-sensitive. If no filename is found matching the wildcard notation, an error is returned. For example, the Files command can display a listing based on supplied file names.

Try using the Files command to display all Fortran source files with the .f90 .

What to do How to do it

Display a listing of all files ending Enter Files -l ≈.f90 in the Work- with the .f90 extension sheet window.

Similarly, multiple Fortran source files may be compiled at once by using a wildcard specification with the f90 command. The following line compiles all files ending with .f90 in the current folder and generates an application.

f90 ≈.f90

When file or path names contain spaces or other special characters such as quotes, they must be enclosed in quotes as in the following examples:

Files “My Disk”:source:≈ F90 “read data.f90” Move “My Disk:the file” “new file”

Fortran User Guide 42 Using the Worksheet

Using MPW Variables Environment variables, text strings that are referenced by a command, can be assigned to MPW commands. Some variables are preassigned (listed in the next section), such as path names and represent certain defaults in MPW. For example, the following variable, {Worksheet}, would be used when you need to direct the output of a command to the Worksheet window.

Other environment variables may be defined and set at any time. Environment variables can be used as a short-cut, for instance, a one-word variable can be set and used for a lengthy directory pathname. The environment variable must be enclosed between braces. In the following example, the preassigned environment variable {MPW} operates as a parameter for the Directory command. When the following line is executed, the current directory is set to the MPW folder.

Directory {MPW} Variables can be expanded and used in conjunction with other character strings. The following command sets the directory to the Tools folder, located within the MPW folder.

Directory {MPW}Tools

User-Defined Variables

The Set command creates user-defined variables. Use the UnSet command to remove variables. This example script defines a new variable, MyVariable, for referencing the Tools folder in the MPW folder.

Set MyVariable {MPW}Tools Directory {MyVariable}

A variable’s definition is maintained until changed with another Set command or quitting MPW. By adding a Set command to the file UserStartup in the MPW directory, you can set a variable that will always be available to you in MPW.

When a variable contains special characters such as spaces, its reference must be enclosed in quotes. If it is not known whether there are special characters, use quotes to insure correct command parsing. For example, the above example should be:

Set MyVariable "{MPW}"Tools Directory "{MyVariable}"

Fortran User Guide Using the Worksheet 43

Preassigned MPW Variables

The following is a useful list of environment variables that are already assigned in MPW that can be referenced as arguments to MPW commands. It is best to not create MPW variables with the same names of the variables in this list.

Variables defined by the shell:

{MPW} Path name for the MPW folder. {Command} File name of the last command executed. {Status} Result of last command executed. A zero means the command was successfully executed. {Active} The file name for the active, or front-most, window. {Aliases} A list of all aliases, separated by commas.

Other variables defined in the Startup or UserStartup files:

{AbsoftTools} Path name for Absoft PowerPC tools. {AbsoftLibraries} Path name for Absoft libraries. {F90Includes} Path name for Fortran 90 include files. {FIncludes} Path name for FORTRAN 77 include files. {ACCIncludes} Path name for C/C++ header files. {FExamples} Path name for Fortran example files. {PPCLibraries} Path name for miscellaneous libraries. {RIncludes} Path name for Rez include files. {Commands} A list of folders separated by commas that are searched to find executable tools and applications, and includes {AbsoftTools} . {Tab} Default tab character size. Initially, this value is 8. {Font} The font name to be used for new windows. {FontSize} The font size to be used for new windows. {User} The name of the current user—same as the name defined in the Chooser. {NLSPATH} Path name for NLS message catalogs.

Creating Scripts The MPW environment can execute more than one command at a time. Any series of commands typed into any window can be executed by selecting the lines and pressing Enter. This listing, called a script, can be created to automate repeated tasks, such as executing multiple tools at once. A group of command lines can be combined and saved as a script file.

Fortran User Guide 44 Using the Worksheet

The Directory command, the command that displays the name of the current folder in the Worksheet window, will be used along with the Files command to demonstrate how to create and initiate a short script.

What to do How to do it

Type the current directory name, the Type Directory, Date and Files on date, and the output of the files separate lines. command on separate lines. Execute the commands. Using the mouse, select all lines and press the Enter key.

This example could be saved as a script file and executed at any time, just like any other built-in command. The name assigned to the script file will be the command name. To execute the script, enter the script file name in the Worksheet and press Enter. Do not save a script file with the same name as a built-in command: the built-in command will override execution of a script file with the same name.

Command Aliases An is an alternative name for a command or a series of commands and specific parameters. Aliases are assigned with the Alias command; this command also will list alias definitions. When an alias is defined, it is only available locally until the command or script is terminated. Aliases can be defined globally by adding them to the Startup and UserStartup Files.

For example, to define an alias for the above script:

What to do How to do it

Define an alias called Stats for a Type Alias Stats "Directory; series of commands. Date; Files" on a new line. Press the Enter key.

Aliases are removed with the Unalias command. To remove an alias, enter the command Unalias followed by the alias name. To remove all aliases, type Unalias and press the Enter key.

Startup and UserStartup are special script files that are invoked every time you begin a session in MPW. These files contain information about default environmental variables and command aliases. It is a good idea to open a copy of these files to view an example of what you can do with the command language in MPW. Be careful when opening and making changes in the startup files: any changes will affect the startup sequence.

Fortran User Guide Using the Worksheet 45

Structured Commands

Commands such as Files or Alias are considered to be simple commands. They consist of a single keyword, followed by zero or more options. Structured commands, on the other hand, are commands that allow you to control the order in which simple commands are executed. An example of a structured command would be the If...Else...End command.

All structured commands are built-in, and usually have more than one keyword. When a structured command is invoked, the command interpreter reads all keywords before they are executed. A thorough listing of MPW's structured commands are given in the MPW Reference Manual.

Command Execution When a command is entered and executed with the Enter key, the MPW shell executes the command in the following sequence:

1. Checks the command for alias substitution according to the lists of defined aliases.

2. Control constructs are evaluated.

3. Any variables or commands executed are replaced with their respective values or output.

4. The command text is divided into individual words separated by blanks.

5. Any word that contains an unquoted ? or ≈ after a variable is executed as a filename pattern.

6. Input and output will be directed or redirected.

7. The command is executed.

Special Characters Special characters in MPW are characters that are reserved in the command language set with special meaning to the MPW shell. When these characters are located in a command line or a line of text, MPW will perform the action associated with the character. A special character in MPW can be disabled; the character's reserved meaning can be nullified by enclosing it within quotes.

Some MPW special characters have been discussed in previous sections and are listed in tables 4-1, 4-2, and 4-3. Other characters, with their meanings, are discussed below.

Fortran User Guide 46 Using the Worksheet

The ∂ Character

One character that may be confusing is the ∂ character (press Option-D). Its meaning is interpreted by the MPW shell depending on the context that it is used in. Its basic function is the Escape character; when used before any character, the ∂ tells the shell to quote the character. However, there are certain exceptions to this rule that are listed below.

∂c Take the single character c literally.

∂[Return] ∂[Return] is discarded and the MPW shell will read the command or text on the next line.

∂t Insert a tab character

∂f Insert a form-feed character

∂n Insert a return character

The § Character

The § character (Option-6) represents the currently selected text in a window. To refer to a text selection in a specific window, type name.§, where name represents the window.

MPW COMMAND REFERENCE This section describes some of the more popular MPW commands for manipulating files, folders, and volumes. These commands provide features found in the Finder (changing directories, opening files), or within the MPW environment. The chapter Building Programs describes the commands that execute important MPW tools, such as the Fortran compiler and the linker.

Although the MPW commands in this chapter are more than sufficient for using Absoft Fortran 90/95, not all of the available commands are documented, nor are all of the options presented for the commands that are discussed. For comprehensive descriptions of these and other MPW commands, see the Macintosh Programmer’s Workshop Manual listed in the bibliography appendix.

Finder commands This list of commands brings the more important features of the Finder into the MPW environment, such as creating directories, working with volumes and finding source files.

Fortran User Guide Using the Worksheet 47

NewFolder

Creates one or more new folders.

Format: NewFolder folder… Example: NewFolder "data files" Creates a folder data files in the current folder. The quotes are necessary since the folder name contains a space. Without the quotes, two folders named data and files would be created.

Files

Displays a list of files and folders to standard output. With no file specified, all files in the current folder are displayed.

Format: Files [-f | -l | -r] [file…] Options: -f Displays full path names for all files. -l Displays all files in long format with the following information: name, type, creator, size, flags, last modification date, and creation date. -r Recursively lists the contents of all sub-folders. Examples: Files -l ≈.f90 Displays, in long format, all Fortran source files in the current folder. Files HD:source:≈.o > Objects Places the names of the object files from the folder HD:source into the Objects file.

Fortran User Guide 48 Using the Worksheet

Delete

Deletes a file or a folder. If a folder is to be deleted, a dialog box will appear, asking you to confirm the command. The -y, -n, and -c options may be used to prevent the dialog from appearing.

Format: Delete [-y | -n | -c] [-p] name… Options: -y Same effect as confirming “yes” to the dialog box for erasing a folder. Using this option will permit deleting folders. -n Same effect as confirming “no” to the dialog box for erasing a folder. Using this option will prevent deleting folders. -c Same effect as confirming “cancel” to the dialog box for erasing a folder. Using this option will stop the Delete command. -p Display progress information while deleting files and folders. Example: Delete ≈.o Deletes all object files ending with .o.

Duplicate

Duplicates a single file to target. If target is a folder, each file is duplicated into the folder.

Format: Duplicate [-y | -n | -c] [-p] file… target Options: -y Same effect as confirming “yes” to the dialog box for overwriting files. Using this option will overwrite existing files or folders. -n Same effect as confirming “no” to the dialog box for overwriting files. Using this option will prevent overwriting existing files or folders. -c Same effect as confirming “cancel” to the dialog box for overwriting files. Using this option will stop these commands. -p Display progress information while duplicating files and folders. Examples: Duplicate -y writedata.f90 BackupDisk:source:output.f90 Copies the file writedata.f90 to the backup disk regardless if the file already existed.

Fortran User Guide Using the Worksheet 49

Eject

Ejects a 3.5-inch disk after flushing and unmounting it. The volume must end with a colon (:) or be a number representing the drive number. Drive 1 is the internal drive. On a system with two internal drives, drive 1 is on the right.

Format: Eject volume… Example: Eject 1 Ejects the disk in drive 1.

Flush

The Flush command clears the MPW tool cache. When you execute a tool and move on to another task, MPW stores the most recently used tools in memory. If you decide to use the tool again, MPW can execute the tool quicker since it is already in memory. The Flush command frees all tools and helps to conserve memory.

Format: Flush

Move

Move files and directories to new location, targetName. If name is a directory, all subdirectories and files are moved as well.

Format: Move name... targetName Example: Move writedata.f90 temp.f90 Renames the file writedata.f90 to temp.f90.

WhereIs

Searches for files or directories according to a pattern. The pattern may be a name of a file, folder, or a certain pattern of either. The search begins with the current directory tree and moves throughout the entire volume. You can use the options below to specify which files or directories will be searched.

Format: Whereis [-c][-d][-v] [-s dir] pattern... Options: -d Matches pattern to directories and files. -c Matches pattern to filenames only. -v Prints the number of items matched during the search. -s dir The search begins at the directory named.

Fortran User Guide 50 Using the Worksheet

Example: whereis -v hello.f90 Searches for the file named hello.f90 with a summary of the number of items matched during the search. whereis -s examples hello.f90 The search for the file hello.f90 begins in the directory examples.

Volumes

The volumes command writes information about the volume or volumes to standard output. The information given is listed alphabetically.

Format: Volumes [-l] [-q] [volume...] Options: -l The drive SCSI number, total size, free space, number of files and number of directories are listed. -q When this option is specified, the command will not quote volume names which contain special characters.

Example: Volumes Displays the names of all mounted volumes.

Rename

Replaces the name of a file or directory with a new name.

Format: Rename name newname Example: Rename hello.f90 greetings.f90 Renames the file hello.f90 to greetings.f90

Fortran User Guide Using the Worksheet 51

Choose

Use the choose command to select AppleShare volumes or printers on a network. If the volume or printer is not mounted, the choose command will automatically mount it.

Format: Choose [options...] name... name takes the form zone:server:volume Options: -list Prints information about the network -type typename Sets the type of network object to choose (e.g. ) -p Writes progress information about the choose command as it executes.

File-related commands File-related commands are useful for manipulating source files. With these commands, you are able to set file attributes, join multiple files, search for specific lines or patterns within files, or sort files.

SetFile

The SetFile command sets different attributes of a file or a number of files.

Format: SetFile [options...] file... Options: -c creator Sets the file creator. The creator must be four characters in length. -t type Sets the file type. The type must be four characters in length. -d date Sets the creation date of the file. The format for the creation date is: mm/dd/yy [hh:mm:ss] [am|pm] -m date Sets the modification date of file. The format for the modification date is the same as the format for the creation date. -l h,v Sets the location of the icon. The values given for the option are h, horizontal, and v, vertical. The values given for h and v must be

Fortran User Guide 52 Using the Worksheet

positive integers and correspond to the offset of the icon from the upper-left corner of the window.

-a attributes Sets the following attributes: L locked V invisible M shared (can run multiple copies) I inited S system B Example: SetFile -c "MPS " -t "MPST" file Sets the creator and type for file.

Catenate

Reads the contents (data fork) of each file and writes them, in order, to standard output. Redirection can be used to write the concatenated output to a file. This command has the opposite effect of the Fsplit tool.

Format: Catenate [file…] Examples: Catenate Sample.f90 Displays the file Sample.f90 in the window beginning on the next line. Catenate read.f90 calc.f90 write.f90 >analyzer.f90 Concatenates the three source files into the file analyzer.f90.

Search

Searches through each file for matches of the regular expression pattern. For all matches, the file name and line number of the match are displayed on standard output. Regular expressions can use the ≈ and ? characters for pattern matching. See the Find menu command in the chapter Using the Editor for more details.

Format: Search [-s | -i] [-r] /pattern/ file… Options: -s The search is done case-sensitive. -i The search is done case-insensitive. -r Reverse the sense of the search by displaying lines that do not contain a match of the pattern.

Fortran User Guide Using the Worksheet 53

Example: Search -i /COMMON/ ≈.f90 Searches all Fortran source files ending in .f90 for the string COMMON in either upper, lower, or mixed case.

Find

Finds a line or text pattern in the specified window and selects it. If no window is specified, the target window is assumed.

Format: Find [-c count] selection [window] Options: -c count For a count of n, find the nth occurrence of the selection.

Examples: Find 332 Selects line 332 in the target window.

Find -c 6 /list/ File.f90 Finds the 6th occurrence of 'list' in the window File.f90 Translate

Translates a specified input string to standard output. Input characters are specified in the src (source) parameter string; output is mapped into the corresponding characters specified by the dst (destination) string.

Format: Translate [option...] src [dst] Options: -s Sets the output file's tab, font, and font size to the same as those of the input file.

Example: translate a-z A-ZucFile Converts lowercase letters to uppercase letters in origFile and writes the translated file to ucFile.

Sort

Sorts or merges files and prints the result on the standard output. If no input file is named, then the command assumes standard input.

Format: Sort [options...] [files...] Options: -check Checks if input has already been sorted. If it is, the return status is set to 0; otherwise it is set to 5. -merge

Fortran User Guide 54 Using the Worksheet

Assumes that input has been sorted and merges the input into the output file. -r Reverses order of comparison. -u Converts characters to uppercase before comparison. -l Converts characters to lowercase before comparison. -o file Specifies the output file. -p Prints progress information. Example: Sort -merge -l Sample.f90 Hello.f90 Merges the files and treats all characters as lowercase.

EnTab

Changes spaces to tabs, and copies the specified file(s) to standard output.

Format: Entab [option...] [file...] Option: -a Sets the minimum run of blanks that will be replaced with a tab. The default is one. -d tabSetting Overrides the input file's default tab setting with tabSetting. -t tabSetting Sets the output file's tab setting to tabSetting. If the tabSetting is 0, the file is left detabbed.

Example: entab -t 6 hello.f90 > tabHello.f90 Entabs the file hello.f90 with a setting of 6 spaces per tab, and writes the results to tabHello.f90.

Count

Counts lines and characters.

Format: Count [-l] [-c] [file] Options: -l Writes the line count only. -c Writes the character count only.

Fortran User Guide Using the Worksheet 55

Example: Count Main.f90 Display.f90 Displays the line count, character count, and totals. Main.f90 43 981 Display.f90 153 3327 Total 196 4308

Compare

Compares the lines of two text files and writes their differences to standard output. Both files are read and compared line by line.

Format: Compare [option...] file1 [file2] Options: -b Treat multiple blanks or tabs as a single blank. -l Ignore case differences. -t Ignore trailing blanks. Example: Compare File File.bak >Differences Compares File and File.bak, and writes the results into a file named Differences.

CompareFiles

Compare two text files and interactively view any differences. A menu named Compare will be added to the menu bar to interactively examine the differences. The menu will be deleted when the command is terminated.

Format: CompareFiles oldFile newFile The Compare menu contains four items: Find next change Finds and highlights the next differences Copy Selection» Replaces the changed text in the new file with the old text «Copy Selection Replaces the old text with the text from the new file Done Closes the files and deletes the Compare menu. If you have made any changes, you will be asked if you want to save them.

Example: CompareFiles Sample.old Sample.new Compares the two files and if there are any differences, the files will be opened side by side.

Fortran User Guide 56 Using the Worksheet

Equal

Compares name to targetName. If they differ the byte at which the difference occurred will be displayed. If targetName is a file, every name must be a file as well. If targetName is a directory and name is a file, the command will check the directory for a file called name .

Format: Equal[-p] name... targetName Option: -p Lists progress information. Example: Equal File1 Dir1 Compares File1 with Dir1:File1

Adjust

Finds and selects the given selection and shifts all lines within the selection to the right by one tab, without changing indentation. The count specifies the number of instances that the selection will be affected. The -l option lets you move lines by any number of spaces to the left or right. If no window is specified, the command applies to the target window (second window from the front).

Format: Adjust [-c count] [-l spaces] selection [window] Options: -c count Repeats the adjust operation count times. -l spaces Every line within the selection will be shifted spaces to the right. Use a negative value to shift the selection to the left.

Example: Adjust 5 Shifts line 5 of the target window to the right by one tab.

Clear

Finds selection and deletes it. If a window is specified, the Clear command acts on that window. If no window is specified, the command operates on the target window (the second from the front).

Format: Clear [-c count] selection [window] Option: -c count Repeats the operation count times.

Fortran User Guide Using the Worksheet 57

Examples: Clear § Deletes the current selection. This acts like the Clear command in the Edit menu, except that the action occurs in the target not the active window. Clear /Begin/:/End/ Selects and deletes from the next Begin through the following End.

Copy

Finds and copies the selection to the Clipboard. This command is equivalent to the Copy command in the Edit menu. To copy files use the Duplicate command.

Format: Copy [-c count] selection [window] Option: -c count Finds and copies the count instance of the selection. Example: Copy § Copies the current selection to the clipboard.

Help commands The two help commands below are some of the most useful within MPW. Use GetErrorText to access error messages for error numbers; use the Help command to access information about MPW commands and features.

GetErrorText

Displays the error messages that correspond to the set of error numbers or ID numbers. By default, GetErrorText assumes the numbers correspond to Macintosh Operating System errors.

Format: GetErrorText [-f filename] [-s filename] ... GetErrorText -i ... Examples: GetErrorText -43 Displays the error messages corresponding to system error -43. GetErrorText -i 28 Displays the error messages corresponding to system ID number 28.

Fortran User Guide 58 Using the Worksheet

Help

Displays help information for command. If command is not specified, information is displayed about Help itself.

Format: Help [command…] Command may also be one of the following: commands List of all MPW commands. expressions Summary of expressions. patterns Summary of patterns (regular expressions). characters Summary of MPW special characters. shortcuts Summary of MPW shortcuts. variables Summary of MPW variables. Note: The Help file should be located in the system folder or in the same directory as the MPW application.

Example: Help Directory Displays help information for the Directory command.

MPW Environment commands The following commands allow you to customize the MPW environment for your personal programming requirements. With these commands you can add special menus, create aliases for commands, or create sounds. The following list also includes the regular quit and shutdown commands.

AddMenu

Adds an item to any menu, creates a new menu with an item, or changes an existing item. When the item is chosen, the command is executed. menuName is the name of a menu and itemName is the name of the new menu item. With an argument missing, AddMenu displays the command for the associated itemName, menuName, or all menus. The new menu item can have keyboard equivalents by appending “/char” to the itemName where char is a keyboard character.

Format: AddMenu [menuName [itemName [command…]]] Examples: Additional examples, including most of the ones shown below are from the file AddMenu in the {MPW}Example:Example folder. AddMenu Tools Displays the commands for the compiler menu items.

Fortran User Guide Using the Worksheet 59

The following is an example using the AddMenu command in a script. It adds a menu command which toggles the setting of the Show Invisibles check box in the Format… dialog of the Edit menu. AddMenu Edit 'Toggle Invisibles/I' ∂ 'If `Format -x a "{Acvtive}"` == "Ail" ; ∂ Format -a AIl "{Acvtive}" ; ∂ Else ; Format -a Ail "{Acvtive}" ; ∂ End’

DeleteMenu

Deletes user-defined menus and items. If the itemName is omitted, then all menu items are deleted. If no menu name or item name is specified, then all user-defined items are deleted.

Format: DeleteMenu [menuName [itemName]] Example: DeleteMenu Tools Deletes the tools menu.

Date

Displays the date and time to standard output. The default of this command shows the date in long form.

Format: Date [[-a | -s][-d |-t] Options: -a Abbreviates the date. Three character abbreviations are used for the month and the day of the week. -s Short date form. Numeric values are given; the day of the week is not shown. -t Writes the time only. -d Writes the date only. Examples: Date Displays the date in the form Monday, January 29, 1990 10:45:32 AM Date -a Displays the date as Mon, Jan 29, 1990 10:45:32 AM Date -s -d Shows 1/29/90

Fortran User Guide 60 Using the Worksheet

Set

Assigns the string value to the variable name. Without specifying value, the value of name is displayed on standard output. If both name and value are not specified, a list of all variables is displayed.

Format: Set [name [value]] Example: Set MyFiles "HD:Tools:source:" Delete "{MyFiles}routine.f90" Sets the variable MyFiles to the path HD:Tools:source: and then uses the variable in a Delete command.

UnSet

Removes any variable definitions. An error will not occur if a definition does not exist for name.

Format: Unset [name...]

Directory

Sets the current folder to folder when specified. When folder is not specified, the current folder is displayed to standard output.

Format: Directory [folder] Examples: Directory Displays the current folder in the window on the next line. Directory HD:MPW:MyFolder Sets the current folder to be HD:MPW:MyFolder. Directory "My Disk":source Sets the current folder to be My Disk:source. Note the necessary quotes around My Disk since it contains a space.

Fortran User Guide Using the Worksheet 61

SetDirectory

Sets the current folder to folder and adds folder to the Directory menu for quick reference.

Format: SetDirectory folder Example: SetDirectory {MyFiles} Using the variable MyFiles as assigned in the example for the Set com- mand, this command adds the name of the folder in MyFiles to the Directory menu.

Alias

An alias is a substitution for a command. Name is the alias for the command or list of commands, word... When name is used as a command name, word will be substituted in its place. The alias can only be used in the file where you defined it. To make an alias available to the entire MPW environment, place the definition in the UserStartup file. You can remove aliases with the Unalias command.

Format: Alias [name [word...]] Example: Alias dir Directory Creates an alias named dir for the command Directory. To use the alias, type dir

Align

Positions all lines in the selection at the same distance from the left margin as the first line in the selection.

Format: Align [-c count] selection [window] Option: -c count Specifies number of times (count) to repeat the selection.

Example: Align 1:4. Will align four lines to the left under the first line as follows:

Before After b = -1.0 b = -1.0 a = sqr(b) a = sqr(b) print *,a print *,a end end

Fortran User Guide 62 Using the Worksheet

Unalias

Removes alias definitions associated with the alias name. If no name is specified, all aliases are removed. The scope of the unalias is limited to the current script.

Format: Unalias [name...] Example: Unalias File Removes the alias File.

Mark

Assigns a marker name to the range of text specified. The new marker name will appear in the Mark menu when that window is the active window.

Format: Mark [-y | -n] selection name [window] Options: -n Answers "no" to any confirmation dialogs, causing the old marker to be left intact. -y Answers "yes" to any confirmation dialogs, causing the old marker to be replaced with the new marker of the same name

Unmark

Removes the markers name... from the list of markers.

Format: Unmark name...window Example: Unmark 'Markers' "{Active}" Removes all markers from the active window.

Commando

The Commando interface lets you operate any MPW command using Macintosh dialog boxes. The Commando dialog box makes it easy to find options.

Format: Commando [commandname] or [commandname] … or [commandname] Option-Enter Example: Commando Rez Displays the dialog box for Rez, as does Rez… and Rez (option-enter)

Fortran User Guide Using the Worksheet 63

DumpFile

Displays the contents of the or data fork of a file.

Format: DumpFile [option...] filename Options: -rf Displays the contents of the resource fork. This is the default. -bf Displays both forks. -a Suppresses ASCII character values. -h Suppresses hexadecimal characters. -p Write progress information to diagnostic output. Example: DumpFile -p ATest Write the contents of the data fork to diagnostic output.

Request

The request command will display a text dialog box in which you may type any text. When you click on the OK button, the text is written to standard output.

Format: Request [-q] [-d default] [message…] Options: -q The dialog box will not show; the command will execute as if you had pressed the OK button. If there is an error, an error message will appear. -d default The text field of the dialog box is initialized to default. The default text will appear in the dialog box; if OK is selected, the default is written to standard output.

Example: Request “FileName?” Brings up a dialog box with the prompt FileName? and a space to enter the name of the file desired.

Fortran User Guide 64 Using the Worksheet

GetFileName

Displays a dialog box to select a given file and return a filename or pathname to standard output.

Format: GetFileName [-t type]...| -p | -d] [-m message] Options: -t type Filters the files according to the type of the file. This option is case sensitive and up to four types may be used. -p Displays a SFPutFile dialog box. -d Displays a SFGetFile dialog for selecting a directory. -m message Specifies a prompt message.

Example: GetFileName Examples Brings up a dialog box listing the files in the directory Examples. Selecting a file from this directory will return the pathname to standard output.

Confirm

The confirm command displays a confirmation dialog box with OK and Cancel buttons. There is no output to this command. This command is useful for scripting.

Format: Confirm [-t] [message] Options: -t Displays a three-way confirmation dialog box, which includes Yes, No, or Cancel.

Alert

Displays an alert box with a prompt message. The alert is displayed until the OK button is clicked. This command can be used in script files.

Format: Alert [-s] [message...] Options: -s The alert runs silently. No beep occurs when the dialog box is displayed.

Example: Alert Please insert disk. Displays an alert box with the message “Please insert disk” and waits for the user to click OK.

Quit

Fortran User Guide Using the Worksheet 65

This command quits from the MPW shell and returns to the Finder. It is equivalent to the Quit command in the File menu.

Format: Quit

Shutdown

This command quits from MPW and shuts down the computer. With the -r option, the machine will reboot.

Format: Shutdown [-r] Options: -r Restarts the machine.

Beep

Produces a note for a particular duration and sound level. If no parameters are given, a simple beep is produced.

Format: Beep [ note [,duration[,level]]] The note can be: • a number indicating the count field for the square wave generator • a string in the following format: [n] letter[# | b] n is a number between -3 and 3 which indicates octaves below or above middle C letter is the note (A-G) # is an optional sharp sign b is an optional flat sign Options: duration in sixtieths of a second—the default is 15. level defined by a number from 0 to 255—the default is 128. Examples: beep Will produce a single beep (using the default beep setting). beep A,180 Will produce an A tone lasting for three seconds.

Window commands Window commands help you to manipulate the multiple-window environment of MPW.

Fortran User Guide 66 Using the Worksheet

New

Opens a new window as the active window. If a name is not specified for the new window, the window will be labeled 'Untitled.' If the specified name already exists, an error will occur.

Format: New [name] Example: New Sample.1 Sample.2 Opens two windows named Sample.1 and Sample.2

Open

Opens a file as the active window. If a name is not specified, a dialog box will appear allowing you to select a file. If name is already open, then that window becomes the active window.

Format: Open [-n |-r][-t] [filename] Options: -n Opens a new window with the title name. -r Opens a read only file called name. -t Opens the window as the target window. This option is identical to the Target command.

Example: Open -t Sample.f90 Opens the file named Sample.f90 as the target window.

Close

Closes the window or windows specified. If no window is specified, the target window is closed. If changes have been made, a dialog box will appear to ask you to confirm the Close command.

Format: Close [-y | -n | -c] [-a | window...] Options: -a Close all open windows. This cannot be used when a window is named. -n Answers "no" to any confirmation dialogs, causing all of the windows to close without saving any changes. -y Answers "yes" to any confirmation dialogs, causing all windows to be saved before closing. -c Answers "cancel" to any dialog boxes, causing any modified windows to be left open.

Example: Close Closes the target window, prompting the user with a dialog box if any changes have been made.

Fortran User Guide Using the Worksheet 67

Close -a -y Saves and closes all open windows.

Print

Prints text files to the selected printer. The file that is to be printed must be in the current directory.

Format: Print [option...] [filename...] Options: -b Prints a border around the page, including the header. -b2 Prints a border around the page; the header appears above the border. -c n Prints n copies of the file. -f name Selects the font for printout. -from n Prints the page number, starting from n. -h Prints headers. The header includes the time of the printing, name and the page number. -s n Specifies the font size. -page n Numbers the from the number (n) specified.

Example: Print -c 3 -f Courier -s 10 -page 1 Sample.f90 Prints 3 copies of the file Sample.f90 in Courier 10 point. The page number begins at 1.

Line

Finds and selects the line n in the target window. This command is generated automatically along with a File command by the Absoft Fortran 90/95 compiler when displaying errors. It may be selected and executed by pressing Enter to immediately show the source line containing the error.

Format: Line n Example: File "readdata.f90"; Line 23 Displays line 23 of the file readdata.f90.

Target

Makes the specified window the target window.

Fortran User Guide 68 Using the Worksheet

Format: Target windowname

File

Sets the filename window to be the target window. The target window is defined to be the second window on the screen. That is the window behind the front-most window. Some MPW commands act on the target window with the most important being the Line command that selects a specific line in the target window. The File and Line commands are generated automatically by the Absoft Fortran 90/95 for errors.

Format: File filename Example: File "readdata.f90"; Line 55 Selects line 55 of the window for the file readdata.f90.

Windows

The Windows command lists the pathname of all windows.

Format: Windows

TileWindows

This command sizes and moves the windows so they are all visible on the screen at once.

Format: TileWindows [-i | windows...] Options: -i Includes the Worksheet window, if no other windows are named. Example: TileWindows -i Makes all windows, including the Worksheet, to be visible.

ZoomWindows

This command enlarges or reduces a window.

Format: ZoomWindows [-s | -b] [window] Options: -s Reduces window back to its original size. -b Enlarges window to full screen size. Example: ZoomWindows -b Sample.f90 Enlarges the window named Sample.f90 to full screen size.

Fortran User Guide Using the Worksheet 69

MoveWindow

Moves a window to a location on the screen. The MoveWindow command moves the upper-left corner of the screen to a location which is specified by a set of coordinates, h and v. h is the horizontal coordinate, v is the vertical coordinate. Both must be integers and separated by a space on the command line. The coordinates (0, 0) are located at the left side of the screen at the bottom of the menu bar. The target window is assumed if no window is named in the command line.

Format: MoveWindow [-i] [h v] [window] Options: -i Overrides errors of the command, for instance, if the coordinates given would place the window off-screen.

Example: MoveWindow 7 20 Sample.f90 Moves the Sample.f90 window to the coordinates (7, 20).

SizeWindow

Sets the size of a given window according to a set of pixel coordinates. h is the horizontal coordinate, v is the vertical coordinate. Both must be integers; use a space to separate the coordinates on the command line. The default window is the target window but you can override the default by naming a window.

Format: SizeWindow [h v] [window] Example: SizeWindow 300 400 {Worksheet} Sizes the Worksheet window to 300 pixels by 400 pixels on the screen.

RotateWindows

Places the front MPW window in the back and brings the second window to the front.

Format: RotateWindows Options: None

Fortran User Guide

71

CHAPTER 5

Using the Compiler

This chapter describes how to use the Absoft Fortran 90/95, FORTRAN 77, and C/C++ compilers to create executable files for the PowerPC processor. Beginning with an overview of the Tools menu, this chapter explains how to compile a small number of Fortran source files into an executable application. Next, compiler error messages are described as well as how to locate the point of error in the source file. The final sections of this chapter describe the compiler options in detail.

COMPILING PROGRAMS Three methods of compiling programs are available: a traditional command line in the MPW Worksheet, the compiler commands in the Tools menu, and makefiles with acm tool. The command line and the compiler commands in the Tools menu are discussed in this chapter. Makefiles and the Absoft make utility, acm, are described in the chapter Building Programs. All three methods allow you to compile source files quickly and easily.

Source file names and compiler options are selected using the mouse pointer with the compiler commands in the Tools menu and with the acm tool. Arguments to the command line version are typed in on the command line.

Using the Worksheet To use a command line version of any of the Absoft compilers, you must enter your commands in the MPW Worksheet described in the chapter Using the Worksheet. The command line version of an individual compiler can be invoked with one of the commands: f95, f77, or acc:

f95 options files

f77 options files

acc options files

The various options are described in the specific compiler options sections later in this chapter.

Like other MPW commands, you can also open a commando interface for any of the individual compilers from the MPW Worksheet:

Type f90 and press Option-Enter.

Type f90, followed by Option-semicolon (an ellipsis), and press Enter.

Fortran User Guide 72 Using the Compiler

Using the Tools Menu

The Tools menu contains commands used to access the Absoft Pro Fortran compilers. This menu has commands for compiling and building programs from source code, library files, and resource files. The Tools menu is divided into four sections.

The first section contains three commands for compiling source code: Compile…, Compile & Launch…, and Compile Again…. When Compile… or Compile & Launch… are selected, a dialog box will appear. The dialog box is part of the Commando interface, a mouse-driven interface that provides a dialog box for every tool and command in MPW. The Compile… and Compile & Launch… commands in the Tools menu invoke the Absoft Pro Fortran compilers for programs that have not previously been compiled. Compile Again… recompiles the last file(s) selected with either the Compile… or Compile & Launch… command using the same options established at that time.

All of these compiler commands can be used to compile a single source file or a number of Fortran 90/95, FORTRAN 77, and/or C/C++ source files. The Compile & Launch… command compiles the source code but goes one step further and launches the newly compiled program.

The second section of the menu contains the command for accessing the Linker… which is used for linking procedure modules together into complete applications or into libraries of modules. The operation of this tool is covered in detail in the chapter Building Programs. However, the linker is normally controlled automatically by the compiler. The third section of the menu contains a command to start the debugger supplied with the compiler: Fx…. The operation of this debugger is described in the chapter Using the Fx Debugger. The fourth section of the Tools menu has commands for working with acm and makefiles: the Create BuildCommands and the Build… command. These are also covered in the chapter Building Programs under the section titled Creating and Using Makefiles. The last section of the menu has only one command, the 72 Column window command, which resizes a text or Worksheet window to show 72 columns of a Fortran program.

Fortran User Guide Using the Compiler 73

THE ABSOFT TOOLS COMMANDO INTERFACE

When the compilers are invoked using the Tools menu, the dialog box for the compiler (the Compile tool) appears. This is a combined interface allowing you to use all of your installed Absoft Pro Fortran compilers from a single interface.

Absoft Pro Fortran compiler dialog box Figure 5-1

When the commando interface is invoked from the worksheet with the f77, f90, or acc tool as described on the previous page, the initial dialog will contain controls for only that compiler. The options that may be selected are the same for both interfaces and are described in the remainder of this chapter.

The Commando dialog has these features:

• Help text is available for any button or field within the dialog box. To display the help text, click and hold on the mouse over the field or button.

• Any button that contains ellipses, such as Source Files(s)…, will bring up additional dialogs.

• As options are checked in the dialog box, they will be added to the Command Line box in the lower portion of the dialog box. The command line can be pasted into any window. See the Using the Worksheet, for guidelines on pasting command lines from the Commando Dialog Boxes.

Fortran User Guide 74 Using the Compiler

Within the Compile dialog box, you can select a list of the source code files to be compiled, along with any specific options to modify the way the compiled applications work. When the Compile button is clicked, the source code will be compiled and linked into an executable program, ready to run. If any errors occur, they are listed in the Worksheet. The features of the Compile dialog box are described below.

Source Files Dialog Box

Use this button to select source files to be compiled. Usually, it will be the first button clicked in the Compile Commando interface. As shown in Figure 5-2, a modified standard dialog box is displayed to select one or more source files.

Source file selection dialog box Figure 5-2

Selecting files to be compiled and linked is simple. Click on each file name in the top list, then click the Add button to add the file to the bottom list. Files in different directories can be added to the bottom list: use the drop menu with the folder (this is the directory title at the top of the dialog) to move to other folders. To remove a file from the bottom list, click on the file within the bottom list and click the Remove button.

When all files to be compiled are listed, click Done. If you choose Cancel, all selections are ignored. After you choose Done or Cancel, the window will return you to the Compile dialog box.

Include Path(s) (-I)

The Compile commando dialog allows you to individually specify the path of include or header files for each Absoft compiler you have installed and will be using. Click on the Include Path(s) button to open the following dialog:

Fortran User Guide Using the Compiler 75

Include and Header File Path Selection Figure 5-3

Use the F77 Include Paths, F90 Include Paths, and ACC Include Paths buttons to select additional directory paths to be searched for FORTRAN 77 and Fortran 90/95 INCLUDE files and C/C++ header files:

Include file path(s) Figure 5-4

The -I option is used to supply a comma separated list of directory paths which are prepended to file names used with the INCLUDE statement.

-Ipath[,path…]

The paths are prepended in the order presented with the -I option when the include file is not first found in the local directory and when it is not itself an absolute path (a full file specification). Paths supplied with the -I option are searched before paths specified with the F90Includes, FIncludes, and ACCIncludes MPW shell variables (see Preassigned MPW Variables in the chapter Using the Worksheet).

Fortran User Guide 76 Using the Compiler

Libraries… Previously compiled object files and libraries of object files are added to the final compiler command by clicking on the Libraries… button. You can choose from the standard libraries supplied with ProFortran or select any other library that may be available on your computer:

Unix Compatibility Library

The Unix library supplied routines compatible with those provided by Sun Microsystems and other Unix based Fortran compilers. Documentation on the routines in this library is available in the Compatibility Libraries manual supplied with Pro Fortran. Source code to all library routines is supplied.

None of the routines in this library are part of the ANSI FORTRAN 77 or Fortran 90/95 standards and should be used with caution if portability between platforms is a concern.

VAX/VMS Compatibility Library

The VMS library has a few additional routines with calling conventions that match VAX FORTRAN. Documentation on the routines in this library is available in the Compatibility Libraries manual supplied with Pro Fortran. Source code to all library routines is supplied.

None of the routines in this library are part of the ANSI FORTRAN 77 or Fortran 90/95 standards and should be used with caution if portability between platforms is a concern.

IMSL MATH/STAT Library

These libraries must be purchased in addition to Pro Fortran. Developed by Visual Numerics, Inc., they comprise the widest selection of mathematical and statistical functionality in the industry

Fortran User Guide Using the Compiler 77

LAPACK Linear Algebra Library

These libraries contain the basic LAPACK and LAPACK90 libraries obtained from www.netlib.org. LAPACK is used for the most common problems in numerical linear algebra including linear equations, linear least squares, eigenvalue, and singular value problems. LAPACK90 is the Fortran 90/95 interface for LAPACK. Source code for these libraries is supplied with Pro Fortran.

Other Libraries…

This button opens the library selection dialog for choosing and adding any individual object file or library of object files available on your computer.

Object and Library File Selection Figure 5-6

The file names selected in this dialog box will usually be libraries of precompiled functions and subroutines, or possibly object files compiled with different language processors.

Text Boxes

The three text boxes within the Compile dialog box name the executable filename, and give additional help information and the equivalent command line.

Executable Filename

The name of the generated executable file can be typed here. If no name is specified, the default name, Link.Out, will be used. The executable file will be placed in the current directory.

Fortran User Guide 78 Using the Compiler

Command Line Box

The command line box shows the equivalent command line for compiling the program. If you select options by clicking the option buttons, the equivalent option letter will show in the box. You can copy the command line to the Worksheet by highlighting the command line and using Copy command in the Edit menu. If you want to copy this line to the Worksheet and execute it at the same time, hold down the Option key while clicking the Compile button.

Help Box

The Help box gives a short description of all the features of the dialog box.

Buttons and Compiler Options

The Compile dialog also contains buttons that allow you to customize how your program will be compiled. There are three types of buttons within the dialog. Radio buttons, as in the Output File box, provide for only one selection at a time. The push buttons, on the left and right sides of the dialog, bring up other dialogs to select one or many compiler options. The two buttons at the bottom of the dialog allow you to invoke the compiler(s) or to Cancel and exit the Compile dialog box.

Output File Box

These radio buttons control the type of application produced by Absoft Pro Fortran. By default, a stand-alone application (the MRWE Application button) is generated and linked with the Macintosh Runtime Window Environment (MRWE) for standard output and input. This is a CarbonLib based application and can be run on any Macintosh operating system from OS 8.6 and up, including OS X. The Output File box allows you to cancel this default and make another choice, such as to generate an MPW tool, or to create an object file to link with other files or place in a library. Refer to the Building Programs chapter for more information on the output file type.

Fortran User Guide Using the Compiler 79

Main Program Box

These radio buttons are used to indicate to the linker the type of main program that will used for an executable program. This specification is necessary to insure that the required startup initialization takes place for the intended application type: Fortran or C.

The Compile Button

Clicking on this button will invoke the Absoft Pro Fortran compiler(s) with all selected options and source files. This is always the last button to be clicked, unless you decide not to invoke compiler by pressing Cancel. By default, executable files generated by Absoft Pro Fortran are placed in the current folder which may be set by using the Set Directory command Directory menu (see the Set Directory command in the chapter Using the Editor and the Directory and SetDirectory commands in the chapter Using the Worksheet).

General Option Buttons

Clicking on this check box in the main Commando interface controls the creation of symbol tables for use with the source level debugger, Fx™. The option is specified on the command line as –g.

Clicking on this button in the main compiler dialog box will quickly turn on compiler optimization. This is the –O option and is the same as choosing this option in the Optimizations dialog.

This button controls the use of optimized vector libraries for the PowerPC G4 processor. If your program is written in Fortran 90/95, uses the IMSL libraries, or uses the LAPACK libraries, special vector libraries will be linked to your program that take advantage of the single precision vector unit in the G4 processor.

ERRORS WHILE COMPILING

Fortran User Guide 80 Using the Compiler

When compiling a program, errors may occur, either in the source file syntax or with the compiler options selected. All errors and warning messages for each compiler are shown in the Worksheet window in a format similar to the following:

goto 10 ^ ### cf90-23 HD:MPW:AbsoftTools:f90fe: ERROR TESTSUB File test.f90 ; Line 2 # Label 10 is not defined in this scoping unit.

(cf90 indicates the name of the message database and 23 is the message number.)

To see the offending source line, highlight the line of the error message within the Worksheet by either selecting it or triple-clicking on it, press the Enter key (not Return), and the source file will be displayed at the point of the error.

Selecting an error message Figure 5-6

If you want to save a list of the errors in the Worksheet window to a text file, choose Save a Copy from the File menu.

The Worksheet window can fill up quickly when there are many errors, especially with repeated compilations. Although the Worksheet can store an immense amount of text, it does consume precious memory. The text can be cleared by choosing the Select All command in the Edit menu and pressing the delete key.

GetErrorText command

The GetErrorText command displays the error messages that correspond to system error numbers, MPW Tools or ID numbers. For example, if you type:

GetErrorText -43

MPW will list the error messages that correspond to the Macintosh Operating System error -43. The GetErrorText command will not display explanations of runtime errors associated with the Absoft Pro Fortran compiler or errors generated by compiling Fortran code. See the appropriate language reference manual for a summary of all compiler messages.

Fortran User Guide Using the Compiler 81

The GetErrorText command operates by locating a file that contains the error messages and displaying the message in the Worksheet window. By default, the GetErrorText command will locate the error messages for Macintosh Operating system errors in a file named SysErrs.Err. MPW can also locate error message files for MPW tools and system ID numbers using special options.

Option What it does

-f filename Lists a tool's error message by accessing the error message file.

-i fdnbr Displays the meaning of the specified System Error handler ID number.

-s filename Finds the filename specified to list the corresponding system error. The default is -s SysErrs.Err.

To locate the error messages for the system ID numbers that are reported in alert dialog boxes, type:

GetErrorText -i 28

This will display the error messages for the system ID number 28.

Appendix D contains a description of all runtime error messages. I/O error messages and Macintosh Operating System error messages are also listed.

ABSOFT FORTRAN 90/95 OPTIONS

Fortran User Guide 82 Using the Compiler

The compiler options detailed in this section give you a great deal of control over the compilation and execution of Fortran 90/95 programs. The options fall into five general categories: Compiler Control, Optimizations, Compatibility, Modules paths and file, and Miscellaneous.

For quick reference, the options listed in the sections that follow are in the order in which they appear in the dialog boxes. Each option is listed with the corresponding option letter(s) and a short description. When an option is checked, the same letters will appear in the Command Line box of the Compile dialog box. Options that take arguments may optionally have a space to separate the option from its argument. The only exceptions are the N and Q options: they cannot have a space between the option and its argument (e.g. -N33).

COMPILER CONTROL...

When clicked, this button in the Compile dialog box displays a dialog of options for controlling various aspects of compiling the Fortran programs. Click on the box next to the option to add the option for compiling.

These options control various aspects of the compilation process such as using disk space instead of memory for intermediate file storage, where include files can be found, and the definition of compiler directive variables. The generation of debugging information, for the symbolic source-level debugger, Fx, is also controlled by compiler control options.

Fortran User Guide Using the Compiler 83

Compiler control dialog Figure 5-7

Suppress warnings (-w)

Suppresses the listing of warning messages. For example, unreachable code will generate a warning message.

Frequent Command-Period checks (-N9)

An application, with the Macintosh Runtime Window Environment (MRWE), may be terminated by pressing Command-Period (a-.). The checks for a-. are done at every Fortran I/O statement. The -N9 option will make the checks for a-. more frequently by setting up a vertical blank interrupt. During the checks for a-, the Macintosh Operating System is given the chance to execute other applications in the cooperative multitasking environment of the Macintosh. Using this option will slow program execution slightly, but the application will remain friendly during long computations that do not use I/O.

Show progress (-v)

Enabling the -v option will cause the f90 command, described above, to display the commands it is sending to the compiler and linker.

Use 32-bit branches (-N11)

In certain types of unusually large program units, the 16-bit addressing capability of the PowerPC branch instructions can be exceeded. In these cases, the compiler will issue a warning and the -N11 compiler option should be used to overcome the limitation. This option should only be used when the compiler issues diagnostics as it will cause more code to be generated than is usually necessary.

Fortran User Guide 84 Using the Compiler

Output Version number (-V)

The -V option will cause the f90 compiler to display its version number. This option may be used with or without other arguments.

Stop on error (-ea)

The -ea option will cause the f90 compiler to abort the compilation process on the first error that it encounters.

Allow greater than 100 errors (-dq)

Normally, the Absoft Fortran 90/95 compiler will stop if more than 100 errors are encountered. This many errors usually indicate a problem with the source file itself or the inability to locate an INCLUDE file. If you want the compiler to continue in this circumstance, select the -dq option.

Default Recursion (-eR)

If you select the -eR option, all FUNCTIONs and SUBROUTINEs are given the RECURSIVE attribute. Normally, if the compiler detects a recursive invocation of a procedure not explicitly given the RECURSIVE attribute, a diagnostic message will be issued. The -eR option disables this.

Use files for temporary storage (-F)

During the course of compilation, the compiler generates intermediate files to store infor- mation between passes. These files are kept in memory in order to reduce compilation time. If system memory is limited, the compiler can be instructed to create these files on disk by specifying the -F option. The names of intermediate files are generated by the Macintosh and begin with "tmp". Since these files are only useful to the compiler, they will be removed automatically at the end of the compilation process. However, if the compiler is unable to delete them, they may be removed manually by dragging their icons to the trash can.

Warn of non-standard usage (-en)

Use of the -en option will cause the compiler to issue a warning whenever the source code contains an extension to the Fortran 90/95 standard. This option is useful for developing code which must be portable to other environments.

Fortran User Guide Using the Compiler 85

Warning level (-znn)

Use the -znn option to suppress messages by message level, where nn is a message level. Diagnostics issued at the various levels are: 0 errors, warnings, cautions, notes, comments 1 errors, warnings, cautions, notes 2 errors, warnings, cautions 3 errors, warnings 4 errors

The default level is -z3; the compiler will issue error and warning diagnostics, but not cautions, notes, and comments. See also the -znn option.

Suppress Warning number(s) (-Znn)

Use the -Znn option to suppress messages by message number, where nn is a message number. This option is useful if the source code generates a large number of messages with the same message number, but you still want to see other messages. See also the -znn option. Generate profiler information (-profile)

Specifying the -profile option will place profile information into a compiled program. Fx, the symbolic debugger, can then be used to gather procedure entry and timing statistics for analysis of runtime bottlenecks. Profiling is introduced at the end of the chapter Macintosh Programming in this manual and described in detail in the chapter Using the Fx Debugger.

Generate procedure trace (-N80)

Specifying the –N80 option will cause the compiler to generate code to write the name of the currently executing procedure to standard out. This option is useful for tracing program execution and quickly isolating execution problems.

OPTIMIZATIONS…

This button displays a dialog of compile time optimizations that generates an application with code that executes quickly. Absoft Fortran 90/95 is a globally optimizing compiler, so various optimizers can be turned on which affect single statements, groups of statements or entire programs. There are pros and cons when choosing optimizations; the application will execute much faster after compilation but the compilation speed itself will be slow. Some of the optimizations described below will benefit almost any Fortran code, while others should only be applied to specific situations.

Fortran User Guide 86 Using the Compiler

Optimizations (-O)

The -O option will cause most code to run faster. It includes common subexpression elimination, loop invariant removal, and strength reduction. This option is selected on the first page of Compile commando dialog.

Optimizations dialog Figure 5-8

COMPATIBILITY…

This button displays a dialog box of options for compiling Fortran programs. These options allow Absoft Fortran 90/95 to accept older or variant extensions of Fortran source code from other computers such as mainframes. Many of these can be used for increased compatibility with Fortran compilers on various mainframe computers.

Compatibility options dialog box Figure 5-9

Fortran User Guide Using the Compiler 87

Source Formats

For compatibility with other Fortran environments and to provide more flexibility, the compiler can be directed to accept source code that has been written in a number of different formats. The two basic formats are free-form and fixed-form.

Free-Form (-f free)

The -f free option instructs the compiler to accept source code written in the format for the Fortran 90/95 Free Source Form. This is the default for file names with an extension of “.f90”.

Fixed-Form (-f fixed)

The -f fixed option instructs the compiler to accept source code written in the format for the Fortran 90/95 Fixed Source Form which is the same as the standard FORTRAN 77 source form.

Fixed line length (-W nn)

Use the -W option to set the line length of source statements accepted by the compiler in Fixed-Form source format. The default value of nn is 72. The other legal values for nn are 80 and 132 — any other value produces an error diagnostic.

Promote REAL and COMPLEX (-N113)

Without an explicit length declaration, single precision REAL and COMPLEX data types default to thirty-two bits or four bytes (KIND=4) and sixty-four bits or eight bytes (KIND=4), respectively. The -N113 option is used to promote these to their double precision equivalents (KIND=8). This option does not affect variables which appear in type statements with explicit sizes (such as REAL (KIND=4) or COMPLEX (KIND=4)).

Demote Double Precision to Real (-dp)

The -dp option will cause variables declared in a DOUBLE PRECISION statement and constants specified with the D exponent to be converted to the default real kind. Similarly, variables declared in a DOUBLE COMPLEX statement and complex constants specified with D exponents will be converted to the complex kind in which each part has the default real kind.

Static storage (-s)

The -s options is used to allocate local variables statically, even if SAVE was not specified as an attribute. In this way, they will retain their definition status on repeated references to the procedure that declared them. Two types of variables are not allocated to static storage: variables allocated in an ALLOCATE statement and local variables in recursive procedures.

Fortran User Guide 88 Using the Compiler

Disable compiler directive (-xdirective)

The -x option is used to disable compiler directive in the source file. directive may be any of the following:

NAME FIXED FREE STATIC

See the section Absoft Fortran 90/95 Compiler Directives for more information on using compiler directives in your source code.

INTEGER*2 and LOGICAL*2 (-i2)

Without an explicit length declaration, INTEGER data types default to thirty-two bits or four bytes (KIND=4). The –i2 option can be used to change this default length to sixteen bits or two bytes (KIND=2). However, an explicit length specification in a type declaration statement always overrides the default data length.

INTEGER*8 and LOGICAL*8 (-i8)

Without an explicit length declaration, INTEGER data types default to thirty-two bits or four bytes (KIND=4). The –i8 option can be used to change the default INTEGER size to 64 bits or 8 bytes (KIND=8). However, an explicit length specification in a type declaration statement always overrides the default data length.

One trip DO loops (-ej)

Fortran 90/95 requires that a DO loop not be executed if the iteration count, as established from the DO parameter list, is zero. The -ej option will cause all DO loops to be executed at least once, regardless of the initial value of the iteration count.

Fortran User Guide Using the Compiler 89

The Miscellaneous button in the Compatibility… dialog box will show the following dialog when clicked:

Miscellaneous Compatibility options dialog box Figure 5-10

Max Internal Handle (-T nn)

This option is used to change the number of handles used internally by the compiler. Under most conditions, the default value of 100000 handles is sufficient to compile even extremely large programs. However, under certain circumstances, this value may be exceeded and the compiler will issue a diagnostic indicating that the value should be increased.

The default value can be increased by powers of ten by specifying the -T nn, where nn is a positive integer constant. When this option is specified, the number of handles will be 100000x10nn bytes.

Temporary string size (-t nn)

In certain cases the compiler is unable to determine the amount of temporary string space that string operations will require. The compiler will assume that the operation in question will require 1024 bytes of temporary string space. This default value can be increased by powers of ten by specifying the -t nn, where nn is a positive integer constant. When this option is specified, the default temporary string size will be 1024x10nn bytes.

Fortran User Guide 90 Using the Compiler

Module File Path(s) (-p)

Click the Module File Path(s) button to specify directory paths that will prepended to files containing module definitions (see Module File(s) below):

Module File Paths Figure 5-11

Module File(s) (-p)

MODULE definitions can be used in multiple files in one of two ways. Either place them in INLCUDE files and include them in files that use them or place them in a source file and compile to create pre-compiled module definition files. Precompiled MODULE files are distinguished with the .mod extension given to them by the compiler when they are created. The advantage of pre-compiled module files is the increased speed of compilation of files that use them.

Fortran User Guide Using the Compiler 91

Click the Module Files(s) button on the F90 dialog to specify which pre-compiled MODULE files you want the compiler to use:

Module Files Figure 5-12

MISCELLANEOUS…

This button displays a dialog box of various Fortran 90/95 options for controlling the representation of externally visible symbols and additional debugging capabilities. These options allow Absoft Fortran 90/95 to accept variant extensions of Fortran 90/95 source code from other computers such as mainframes. Many of these can be used for increased compatibility with programs written in other programming languages.

Fortran User Guide 92 Using the Compiler

Escape Sequences in Strings (-YCSLASH=1)

If the -YCSLASH=1 option is turned on, the compiler will transform the following escape sequences marked with a ‘\’ embedded in character constants: \a Audible Alarm (BEL, ASCII 07) \b Backspace (BS, ASCII 8) \f Form Feed (FF, ASCII 12) \n Newline (LF, ASCII 10) \r Carriage Return (CR, ASCII 13) \t Horizontal Tab (HT, ASCII 09) \v Vertical Tab (VT, ASCII 11) \xh[h] Hexidecimal, up to 2 digits \o[o[o]] Octal number, up to 3 digits \\ Backslash

The default is -YCSLASH=0.

No Dot for Percent (-YNDFP=1)

This option instructs the compiler to disallow the use of a ‘.’ (period) as a structure field component dereference operator. The default is to allow both ‘%’ (percent), which is the Fortran 90/95 standard, and a period which is typically used with DEC style RECORD declarations. The use of a period may cause certain Fortran 90/95 conforming programs to be mis-interpreted (a period is used to delineate user defined operators and some intrinsic operators). The default is -YNDFP=0. This switch implements Fortran 90/95 standard parsing for structure component referencing.

COMMON Block Name Character Case (-YCOM_NAMES={ ASIS | UCS | LCS})

The -YCOM_NAMES option is used to specify how the external names COMMON blocks are emitted. The default (-YEXT_NAMES=UCS) is to emit COMMON block names entirely in upper case. Set this option to LCS to emit names entirely in lower case. Use ASIS to emit the names in the character of the source file.

COMMON Block Name Prefix (-YCOM_PFX=string)

The -YEXT_PFX option can be used to prepend a user-specified string to the external representation of COMMON block names.

COMMON Block Name Suffix (-YCOM_SFX=string)

The -YEXT_SFX option can be used to append a user-specified string to the external representation of COMMON block names.

Fortran User Guide Using the Compiler 93

Check Array Boundaries (-Rb)

When the –Rb compiler option is turned on, code will be generated to check that array indexes are within the bounds of an array. Assumed size arrays whose last dimension is * cannot be checked. In addition, file names and source code line numbers will be displayed with all run time error messages.

Check Array Conformance (-Rc)

The –Rc compiler option is used to check array conformance. When array shapes are not known at compile time and where they must conform, runtime checks are created to insure that two arrays have the same shape.

Check Substrings (-Rs)

When the –Rs compiler option is turned on, code will be generated to check that character substring expressions do not specify a character index outside of the scope of the character variable or character array element.

Check Pointers (-Rp)

Use –Rp compiler option is used to generate additional program code to insure that Fortran 90 style POINTER references are not null.

YEXT_NAMES={ASIS | UCS | LCS}

The -YEXT_NAMES option is used to specify how the external names of globally visible symbols, such as FUNCTION and SUBROUTINE names, are emitted. By default, names are emitted entirely in upper case. Set this option to LCS to emit names entirely in lower case. Set this option to ASIS to force external names to emitted exactly as they appear in the source program. This option controls how external names will appear to other object files.

External Symbol Suffix (-YEXT_SFX=string)

The -YEXT_SFX option can be used to append a user specified string to the external representation of external procedure names.

Other F90/95 Options The following options are not available with the graphical interface to the compiler but may used with the command line interface or the make facility (See the chapter, Building Programs).

Fortran User Guide 94 Using the Compiler

-YDEALLOC= {MINE | ALL | CACHE})

This option is used to control the underlying runtime memory management associated with the Fortran 95 ALLOCATE and DEALLOCATE statements. By default the runtime caches memory which has been deallocated (CACHE). Specifying MINE will cause all user allocated memory to be returned via a call to free(2) when a call to DEALLOCATE is executed. Specifying ALL will cause all user allocated memory to be returned via a call to free(2) and return any compiler allocated memory that has been cached. The tradeoff is minimizing memory use (ALL/MIME) versus speed of execution (CACHE).

YPEI={0|1}

Pointers Equivalent to Integers. This option controls whether or not the compiler will allow or accept a CRI style pointer to be equivalent to an integer argument. By default the Absoft Fortran 90/95 compiler allows this. Even with this relaxed error checking the compiler will correctly choose the right interface for the following example:

interface generic subroutine specific1(i) integer i end subroutine specific1 subroutine specific2(p) integer i pointer (p,i) end subroutine specific2 end interface call generic(i) call generic(loc(i)) end

Regardless of the switch setting, this example will compile and the executable generated will be equivalent to:

call specific1(i) call specific2(loc(i))

ABSOFT FORTRAN 90/95 COMPILER DIRECTIVES Compiler directives are lines inserted into source code that specify actions to be performed by the compiler. They are not Fortran 90/95 statements. If you specify a compiler directive while running on a system that does not support that particular directive, the compiler ignores the directive and continues with compilation.

A compiler directive line begins with the characters CDIR$ or !DIR$. How you specify compiler directives depends on the source form you are using.

If you are using fixed source form, indicate a compiler directive line by placing the characters CDIR$ or !DIR$ in columns 1 through 5. If the compiler encounters a nonblank character in column 6, the line is assumed to be a compiler directive continuation line. Columns 7 and beyond can contain one or more compiler directives. If you are using the

Fortran User Guide Using the Compiler 95 default 72 column width, characters beyond column 72 are ignored. If you have specified 80 column lines, characters beyond column 80 are ignored.

If you are using free source form, indicate a compiler directive line by placing the characters !DIR$ followed by a space, and then one or more compiler directives. If the position following the !DIR$ contains a character other than a blank, tab, or newline character, the line is assumed to be a compiler directive continuation line.

If you want to specify more than one compiler directive on a line, separate each directive with a comma.

NAME Directive

The NAME directive allows you to specify a case-sensitive external name in a Fortran program. You can use this directive, for example, when writing calls to C routines. The case-sensitive external name is specified on the NAME directive, in the following format:

!DIR$ NAME (fortran=“external” [,fortran=“external”]...)

where: fortran is the name used for the object throughout the Fortran program whenever the external name is referenced.

external is the external name.

FREE Directive

The FREE directive specifies that the source code in the program unit is written in the free source form. The FREE directive may appear anywhere within your source code. The format of the FREE directive is:

!DIR$ FREE

You can change source form within an INCLUDE file. After the INCLUDE file has been processed, the source form reverts back to the source form that was being used prior to processing the INCLUDE file.

FIXED Directive

The FIXED directive specifies that the source code in the program unit is written in the fixed source form. The FIXED directive may appear anywhere within your source code. The format of the FIXED directive is:

!DIR$ FIXED

You can change source form within an INCLUDE file. After the INCLUDE file has been processed, the source form reverts back to the source form that was being used prior to processing the INCLUDE file.

Fortran User Guide 96 Using the Compiler

STACK Directive

The STACK directive causes the default storage allocation to be the stack in the program unit that contains the directive. This directive overrides the -s command line option in specific program units of a compilation unit. The format for this compiler directive is:

!DIR$ STACK

ABSOFT FORTRAN 77 OPTIONS The compiler options detailed in this section give you a great deal of control over the compilation and execution of FORTRAN programs. The options fall into three general categories: Compiler Control, Optimizations, and Compatibility.

For quick reference, the options listed in the sections that follow are in the order in which they appear in the dialog boxes. Each option is listed with the corresponding option letter(s) and a short description. When an option is checked, the same letters will appear in the Command Line box of the Compile dialog box. Options which take arguments (e.g. - h 4 or -o file) must have a space to separate the option from the argument. The only exception are the N options: they do not have a space between the option and the argument (e.g. -N33).

This button controls the use of optimized vector libraries for the PowerPC G4 processor. If your program is written in Fortran 90/95, uses the IMSL libraries, or uses the LAPACK libraries, special vector libraries will be linked to your program that take advantage of the single precision vector unit in the G4 processor.

Fortran User Guide Using the Compiler 97

COMPILER CONTROL...

When clicked, this button in the Compile dialog box displays a dialog of options for controlling various aspects of compiling the FORTRAN programs. Click on the box next to the option to add the option for compiling.

These options control various aspects of the compilation process such as using disk space instead of memory for intermediate file storage and the definition of compiler directive variables. The generation of debugging information, for the symbolic source-level debugger, Fx, is also controlled by compiler control options.

Compiler control dialog Figure 5-13

Suppress warnings (-w)

Suppresses the listing of warning messages. For example, unreachable code or a missing on a FORMAT statement generate warning messages. Compile time diagnostic messages are divided into two categories: errors and warnings. Error messages indicate that the compiler was unable to generate an output file. Warning messages indicate that some syntactic element was not appropriate, but the compiler was able to produce an output file.

Suppress alignment warnings (-A)

The compiler normally will issue a warning message if a variable is aligned on a boundary which does not match its size. Misaligned storage locations slow down memory access and can cause difficulty if you attempt to port the program to other computers. Use the -A option to suppress the listing of this type of warning only.

Fortran User Guide 98 Using the Compiler

Use 32-bit branches (-N11)

In certain types of unusually large program units, the 16-bit addressing capability of the PowerPC branch instructions can be exceeded. In these cases, the compiler will issue a warning and the -N11 compiler option should be used to overcome the limitation. This option should only be used when the compiler issues diagnostics as it will cause more code to be generated than is usually necessary.

Generate procedure trace (-N124)

Specifying the -N124 option will cause the compiler to generate code to write the name of the currently executing procedure to standard out. This option is useful for tracing program execution and quickly isolating execution problems.

Generate profiler information (-p)

Specifying the -p option will place profile information into a compiled program. Fx, the symbolic debugger, can then be used to gather procedure entry and timing statistics for analysis of runtime bottlenecks. Profiling is introduced at the end of the chapter Macintosh Programming in this manual and described in detail in the chapter Using the Fx Debugger.

Check array boundaries (-C)

When the -C compiler option is turned on, code will be generated to check that array indexes are within the bounds of an array. Exceptions: arrays whose last dimension is * and dummy arguments whose last dimension is 1 cannot be checked. In addition, file names and source code line numbers will be displayed with all run time error messages.

Full Debug with Fx (-g)

Specifying the -g option on the command line will cause the compiler to generate symbol information for Fx. Fx is supplied with the Absoft Pro Fortran development system. Debugging Fortran applications is introduced at the end of the chapter Macintosh Programming in the section titled Debugging and completely described in the chapter Using the Fx Debugger. This option implicitly enables the -m option for suppressing delayed stores.

Min Debug with Fx (-gmin)

Specifying the -gmin option on the command line will cause the compiler to generate line number information only for Fx – variables cannot be examined or modified. However, full optimization can used with this option and program execution can be profiled with Fx. Fx is supplied with the Absoft Pro Fortran development system. Debugging Fortran applications is introduced at the end of the chapter Macintosh Programming in the section titled Debugging and completely described in the chapter Using the Fx Debugger.

Fortran User Guide Using the Compiler 99

Info for unused structures (-N111)

Normally, the compiler does not place information in the debugger symbol tables for structures which are only declared, but never have storage associated with them. This keeps the symbol tables to a manageable size when include files are used to make structure declarations. The -N111 option can be used to force the compiler to place information in the debugger symbol tables for all structures whether they have associated storage or not. This option is only enabled when the -g option has been selected.

Suppress delayed stores (-m)

In certain cases, the compiler will delay generating code which will store data from a register to memory as long as possible. The result of doing this may make the data inaccessible to other tasks. If it is important that data be written to memory as soon as it changes value, the use of the -m compiler option will force the compiler not to delay register storage. Use of this option will slow execution speed.

Conditional compilation (-x)

Statements containing an X or a D in column one are treated as comments by the compiler unless the -x compiler option is selected. This option allows a restricted form of conditional compilation designed primarily as a means for easily removing debugging code from the final program. When the -x option is selected, any occurrence of an X or a D in column one is replaced by a blank character. The only source formats for which conditional compilation is valid are standard FORTRAN 77, VAX Tab-Format, and wide format. The compiler also incorporates a complete set of statements for conditional compilation which are described in the Conditional Compilation Statements section of the FORTRAN 77 Program chapter in the FORTRAN 77 Language Reference Manual.

Max Internal Handle (-T nn)

This option is used to change the number of handles used internally by the compiler. Under most conditions, the default value of 20000 handles is sufficient to compile even extremely large programs. However, under certain circumstances, this value may be exceeded and the compiler will issue a diagnostic indicating that the value should be increased.

Fortran User Guide 100 Using the Compiler

The Miscellaneous button in the Compiler Control… dialog box will show the following dialog when clicked:

Miscellaneous Compiler Control options dialog box Figure 5-14

Output

The normal output of the compiler is directed to standard output (the Worksheet window). This pop-up menu can be used to redirect this normal progress output of the compiler to a different window or to a file. (See ROUTING COMMAND OUTPUT in the chapter Using the Worksheet for a discussion of the various output options.)

No compiler standard output (-q)

The Absoft Fortran 77 compiler normally displays information to standard output (the Worksheet window) as it compiles an application. Enabling the -q option will suppress any messages printed to standard output. Errors will still be printed to standard diagnostic, however.

Show progress (-v)

Enabling the -v option will cause the f77 shell script, described earlier in this chapter, to display the commands it is sending to the compiler and linker.

Fortran User Guide Using the Compiler 101

Frequent Command-Period checks (-N9)

An application, with the Macintosh Runtime Window Environment (MRWE), may be terminated by pressing Command-Period (a-.). The checks for a-. are done at every FORTRAN I/O statement listed in the Input/Output and Format Specifications chapter of the FORTRAN 77 Language Reference Manual. The -N9 option will make the checks for a-. more frequently by setting up a vertical blank interrupt. During the checks for a-., the Macintosh Operating System is given the chance to execute other applications in the cooperative multitasking environment of the Macintosh. Using this option will slow program execution slightly, but the application will remain friendly during long computations that do not use I/O.

Use files for temporary storage (-F)

During the course of compilation, the compiler generates intermediate files to store infor- mation between passes. These files are kept in memory in order to reduce compilation time. If system memory is limited, the compiler can be instructed to create these files on disk by specifying the -F option. The names of intermediate files are generated by the Macintosh and begin with "tmp". Since these files are only useful to the compiler, they will be removed automatically at the end of the compilation process. However, if the compiler is unable to delete them, they may be removed manually by dragging their icons to the trash can.

Define Compiler directives (-Dname[=value])

Use this scrollable text box to enter the names and optional values of conditional compilation variables:

The -D option is used to define conditional compilation variables from the command line. value can only be an integer constant. If value is not present, the variable is given the value of 1. Conditional compilation is described in the Conditional Compilation Statements section in the FORTRAN 77 Program chapter of the FORTRAN 77 Language Reference Manual.

Generate object files (-c)

The -c option causes the compiler to suppress creation of an executable file and leave object files for each compiled file. This option should be used when compiling subpro- grams for placing into a library or linking explicitly. The object file will have the same name as the FORTRAN source file with the characters “.o” appended. In the main Fortran compiler Commando dialog, this option appears as the button “No executable”.

Specifying the executable file name (-o name)

The compiler will provide the default name Link.Out for an executable file produced by a successful and complete compilation. Specifying the -o name option, where name is a

Fortran User Guide 102 Using the Compiler

Macintosh file name, will cause the compiler to produce an executable file called name. This option appears in the main Fortran compiler Commando dialog as the executable file name.

OPTIMIZATIONS…

This button displays a dialog of compile time optimizations that generates an application with code that executes quickly. Absoft Fortran 77 is a globally optimizing compiler, so various optimizers can be turned on which affect single statements, groups of statements or entire programs. There are pros and cons when choosing optimizations; the application will execute much faster after compilation but the compilation speed itself will be slow. Some of the optimizations described below will benefit almost any FORTRAN code, while others should only be applied to specific situations.

Optimizations dialog Figure 5-15

You may want to ignore optimizations during program development or for compilations of FORTRAN source code ported to the Macintosh to save time. When a FORTRAN program is executing correctly and has been debugged, turn on optimizations for improved run-time performance. Most programs achieve their largest initial performance gain when Basic optimizations is selected. In general, all optimizations should be selected carefully.

Basic optimizations (-O)

The -O option is a group of basic optimizations which will cause most code to run faster without the expense of application size or memory usage. These include common subexpression elimination, loop invariant removal, and strength reduction.

DATA treated as constants (-N5)

The -N5 compiler option enables the optimizer to propagate as constants those variables initialized in DATA statements which are not redefined. For example:

Fortran User Guide Using the Compiler 103

Original code: Becomes: SUBROUTINE DIVIDE(A) SUBROUTINE DIVIDE(A) INTEGER A(50),B,C INTEGER A(50),B,C

DATA B,C/100,10/ DATA B,C/100,10/

DO I=1,50 DO I=1,50 A(I) = A(I)/B-I*C A(I) = A(I)/100-I*10 END DO END DO RETURN RETURN END END

This option is automatically turned on with the -O option for basic optimizations.

Function decomposition (-N18)

The -N18 compiler option causes intrinsic functions to be decomposed in line wherever possible. For example:

Original code: Becomes: I = MOD (J,K) I = (J-((J/K)*K))

This option is automatically turned on with the -O option for basic optimizations.

Loop unrolling (-U and -h nn and -H nn)

The Absoft Fortran 77 compiler has the ability to automatically unroll some of the loops in your source code. Loops may be unrolled by any power of two. Generally it is beneficial to unroll loops which execute a large number of iterations, while the benefit is small for loops which iterate only a few times. Due to this, only innermost loops are considered for unrolling. The -h nn option will cause the compiler to unroll your innermost loops nn times, where nn is any power of two. The -H nn option will cause the compiler to consider loops containing nn or fewer statements for unrolling. When the -O option is used, the default is to only consider loops of a single line and unroll them four times. Using the -U option is equivalent to using -h 2 -H 10, causing innermost loops of ten or fewer lines to be unrolled twice. Loop unrolling will provide a speed increase in most cases, but will make your application larger and it will require more memory to compile. Consider the following example:

Fortran User Guide 104 Using the Compiler

Original code: Becomes: SUBROUTINE SUB(A,N,X) SUBROUTINE SUB(A,N,X) INTEGER A(100) INTEGER A(100)

DO i=1,N DO i=1,MOD(N,4) A(i) = X*A(i) A(i) = X*A(i) END DO END DO RETURN DO i=4,N-(MOD(N,4)),4 END A(i) = X*A(i) A(i+1) = X*A(i+1) A(i+2) = X*A(i+2) A(i+3) = X*A(i+3) END DO RETURN END

At least three comparisons and three branch instructions are saved each time the second loop is executed. Note that if your code contains extended range DO loops, unrolling loops will invalidate your program.

COMPATIBILITY…

This button displays a dialog box of options for compiling FORTRAN programs. These options allow Absoft Fortran 77 to accept older or variant extensions of FORTRAN source code from other computers such as mainframes. Many of these can be used for increased compatibility with FORTRAN compilers on various mainframe computers.

Compatibility options dialog box Figure 5-16

Fortran User Guide Using the Compiler 105

Folding to lower case (-f)

The -f option will force all symbolic names to be folded to lower case. By default, the compiler considers upper and lowercase characters to be unique, an extension to FORTRAN 77. If you do not require case sensitivity for your compilations or specifically require that the compiler not distinguish between case, as in FORTRAN 77, use this option. This option should be used for compatibility with VAX and other FORTRAN environments.

Static storage (-s)

In FORTRAN 66, all storage was static. If you called a subroutine, defined local variables, and returned, the variables would retain their values the next time you called the subroutine. FORTRAN 77 establishes both static and dynamic storage. Storage local to an external procedure is dynamic and will become undefined with the execution of a RETURN statement. The SAVE statement is normally used to prevent this, but the -s compiler option will force all program storage to be treated as static and initialized to zero. The -N1 compiler option causes the definition of variables initialized in DATA statements to be maintained after the execution of a RETURN or END statement. This option should be used for compatibility with VAX and other FORTRAN environments.

Use record lengths in I/O (-N3)

If the -N3 compiler option is used, record length information will be included for sequen- tial, unformatted files as if the “BLOCK=-1” specifier were implicitly included in all appropriate OPEN statements. See the Input/Output and Format Specifications chapter of the FORTRAN 77 Language Reference Manual for more information about the BLOCK=-1 specifier. This option should be used for compatibility with VAX and other FORTRAN environments.

RECL Defines 32-bit words (-N51)

If the -N51 compiler option is used, the “RECL” specifier will be interpreted as the number of 32 bit words in a record for UNFORMATTED, DIRECT access files. Without this option, RECL defines the number of bytes in a record. This option should be used for compatibility with VAX and other FORTRAN environments.

Folding to upper case (-N109)

By default, the compiler considers upper and lowercase characters to be unique, an extension to FORTRAN 77. If you do not require case sensitivity for your compilations or specifically require that the compiler not distinguish between case, as in FORTRAN 77, including the -N109 option on the compiler invocation command line will force all symbolic names to be folded to upper case.

Fortran User Guide 106 Using the Compiler

One-trip DO loops (-d)

FORTRAN 66 did not specify the execution path if the iteration count of a DO loop, as established from the DO parameter list, was zero. Many processors would execute this loop once, testing the iteration count at the bottom of the loop. FORTRAN 77 requires that such a DO loop not be executed. The -d option will cause all DO loops to be executed at least once, regardless of the initial value of the iteration count.

INTEGER*2 and LOGICAL*2 (-i2 )

Without an explicit length declaration, INTEGER and LOGICAL data types default to thirty- two bits (four bytes). The –i2 option is used to change this default length to sixteen bits (two bytes). It should be noted that this refers only to storage types. During the execution of a program, all sixteen and eight bit values are extended to thirty-two bits before any operation involving them is performed.

INTEGER*8 and LOGICAL*8 (-i8 )

Without an explicit length declaration, INTEGER and LOGICAL data types default to thirty- two bits (four bytes). The –i8 option is used to change this default length to sixty-four bits (eight bytes).

Zero extend INTEGER*1 (-N102)

Normally, INTEGER*1 variables are sign extended when they are loaded from memory, providing for integers which range from -128 to 127. In order to provide compatibility with other implementations of FORTRAN, the -N102 option can be used to direct the compiler to zero extend these variables when they are loaded, making them essentially unsigned entities with a range of 0-255.

Warn of non-ANSI usage (-N32)

Use of the -N32 option will cause the compiler to issue a warning whenever the source code contains an extension to the ANSI FORTRAN 77 standard (American National Standard Programming Language FORTRAN, X3.9-1978). This option is useful for developing code which must be portable to other environments.

Extern Globals (-M)

The -M option will cause the compiler to treat all COMMON blocks declared in the program as though they where declared with the GLOBAL statement. The GLOBAL statement allows variables declared in shared libraries to be accessed by other program units.

Fortran User Guide Using the Compiler 107

Source Formats

For compatibility with other FORTRAN environments and to provide more flexibility, the compiler can be directed to accept source code which has been written in a variety of different formats. The default setting is to accept only ANSI standard FORTRAN source code format. See the FORTRAN 77 Program chapter of the FORTRAN 77 Language Reference Manual for more information on alternative source code formats.

Fortran 90 Free-Form (-8)

Use of the -8 option instructs the compiler to accept source code written in the format for the Fortran 90/95 Free Source Form.

IBM VS Free Form (-N112)

Use of the -N112 option causes the compiler to accept source code in the form specified by IBM VS Free Form.

VAX Tab-Format (-V)

Use of the -V option causes the compiler to accept source code in the form specified by VAX Tab Format.

Wide format (-W)

Use of the -W option causes the compiler to accept statements which extend beyond column 72 up to column 132.

Set Big-Endian (-N26)

Use this option to force the compiler to consider the byte ordering of all unformatted files to be big-endian by default . The CONVERT specifier in the OPEN statement may be used to override this setting for individual files.

Set Little-Endian (-N27)

Use this option to force the compiler to consider the byte ordering of all unformatted files to be little-endian by default . The CONVERT specifier in the OPEN statement may be used to override this setting for individual files.

Set COMMON block name (-N22)

The -N22 option is used to change the scheme the compiler employs for generating global names for COMMON blocks. The default is to prepend the characters “_C” to the COMMON block name. This option cau1se the compiler to append a single underscore (_) instead. This option is intended primarily for compilers installed on Linux-based systems.

Fortran User Guide 108 Using the Compiler

The Miscellaneous button in the Compatibility… dialog box will show the following dialog when clicked:

Miscellaneous Compatibility options dialog box Figure 5-17

Evaluate left-to-right (-N20)

When two or more operators of equal precedence appear consecutively in an arithmetic expression, the -N20 forces the compiler to evaluate the operators from left to right (except for the exponentiation operators), regardless of whether it is the most efficient method or not.

Don’t generate FMA instructions (-Q51)

Use of the -Q51 option will cause the compiler not to use floating-point multiply-add type of instructions. Since there is no rounding performed between the multiplication and addition during the execution of these instructions, numeric results will vary depending on where they are used.

Double precision transcendentals (-N2)

The -N2 option causes the compiler to use double precision or double complex transcen- dental intrinsic functions, overriding single precision and complex type specifications. This provides an extra bit of precision in some cases and is compatible with some C environments.

Fortran User Guide Using the Compiler 109

Sign extend BYTE() & WORD() (-N7)

The -N7 compiler option causes the compiler to extend the sign of a value returned from the intrinsic functions BYTE and WORD. This option has no effect on the memory assign- ment statements described in the Expressions and Assignments chapter of the FORTRAN 77 Language Reference Manual.

DATA variables are static (-N1)

The -N1 compiler option causes all variables initialized with DATA statements to be stored as static variables.

Promote REAL and COMPLEX (-N113)

Without an explicit length declaration, single precision REAL and COMPLEX data types default to thirty-two bits (four bytes) and sixty-four bits (eight bytes), respectively. The - N113 option is used to promote these to their double precision equivalents: DOUBLE PRECISION and DOUBLE COMPLEX. This option does not affect variables which appear in type statements with explicit sizes (such as REAL*4 or COMPLEX*8).

Escape sequences in strings (-K)

If the -K option is turned on, the compiler will transform certain escape sequences marked with a ‘\’ embedded in character constants. For example ‘\n’ will be transformed into a newline character for your system. Refer to the FORTRAN 77 Program chapter FORTRAN 77 Language Reference Manual for more information on the escape sequences which are supported.

Allows CASE without DEFAULT (-N4)

By default, a run-time error is reported if a CASE DEFAULT statement is not present in a block CASE structure when a match is not found. The -N4 causes control of execution to be transferred to the statement following the END SELECT statement when a CASE DEFAULT statement is not present and no match is found, preventing such a run-time error.

Allows UNIT= without FMT= (-N16)

If the -N16 compiler option is used, the format specifier FMT= may be omitted in an I/O statement when the unit specifier UNIT= is present.

Align COMMON variables (-N34)

If a COMMON block is defined in a manner that causes a misaligned storage location, the -N34 option can be used to insert space to eliminate the misalignment. This option may invalidate your code if the same COMMON block is defined differently in different program units.

Fortran User Guide 110 Using the Compiler

Pascal keyword significant (-N17)

The default behavior of the compiler is to accept the PASCAL keyword, but to ignore it. The -N17 option causes the compiler to fold the procedure name to upper case and to reverse the argument list which is typical of Pascal language interfaces.

Pascal declaration is error (-N21)

The PASCAL keyword is used by MacFortran II, the Absoft compiler for 68000 based Macintosh systems, to inform the compiler of a non-standard function interface, typically a toolbox call. The PowerPC toolbox interface conforms to an ABI (Application Binary Interface) which is well defined and consistent between programming languages. Hence, the PASCAL keyword is no longer required. The default behavior of the compiler is to accept the PASCAL keyword, but to ignore it. The -N21 option can be used to cause the compiler to issue an error when it encounters the keyword PASCAL.

Append underscore to names (-N15)

Use of the -N15 option will cause the compiler to define SUBROUTINE and FUNCTION names with a trailing underscore. This option can be used to avoid name conflicts with the system libraries or to interface with other FORTRAN environments.

Temporary string size (-t nn)

In certain cases the compiler is unable to determine the amount of temporary string space that string operations will require. This undetermined length occurs when the REPEAT function is used or when a CHARACTER*(*) variable is declared in a subroutine or function. In these cases, the compiler will assume that the operation in question will require 1024 bytes of temporary string space. Specifying the -t nn option, where nn is a positive integer constant, can change this default value. When this option is specified, the default temporary string size will be nn bytes.

STRUCTURE Alignment

Normally, the fields in a STRUCTURE are aligned based on the standard for C. This may cause spaces to be left between structure elements and space to be added to the end of a structure. Several options are available to force structure fields to be “aligned” — allocated with no space or set a amount of space between them You can also use the conditional compilation directives $PACK and $PACKOFF to control the packing of individual structures (see the section Conditional Compilation Directives in the FORTRAN 77 Program chapter of the FORTRAN 77 Language Reference Manual). The use of this option may cause misaligned storage locations.

Align STRUCTURE fields to 1 byte boundaries (-N56)

The –N56 option will force structure fields to be completely “packed”. No padding will occur between fields. The use of this option may cause misaligned storage locations.

Fortran User Guide Using the Compiler 111

Align STRUCTURE fields to 2 byte boundaries (-N57)

The –N57 option will force structure fields to be aligned to 2-byte boundaries. Fields beginning at odd addresses will be aligned to the next even address. The use of this option may cause misaligned storage locations for fields greater than 2 bytes in length..

Align STRUCTURE fields to 4 byte boundaries (-N58)

The –N58 option will force structure fields to be aligned to 4-byte boundaries. Fields not beginning at a modulo 4 address will be aligned to the next 4-byte boundary. The use of this option may cause misaligned storage locations for fields greater than 4 bytes in length..

Align STRUCTURE fields to 8 byte boundaries (-N59)

The –N59 option will force structure fields to be aligned to 8-byte boundaries. Fields not beginning at a modulo 8 address will be aligned to the next 8-byte boundary.

Other F77 Options

The following options are not available on the F77 option pages but may be used with the command line interface or the make facility (See the chapter, Building Programs).

Warnings for Undeclared Variables (-N114)

If the IMPLICIT NONE statement appears in a program unit, the compiler will issue an error diagnostic whenever it encounters an undeclared variable. If you specify the –N114 option, the compiler will issue a warning diagnostic.

Pad Source Lines (-N115)

Use the –N115 option to pad source lines to column 72 with spaces (or 132 with the –W option). By default, the compiler considers only the characters actually present in the source file. This option is useful when porting certain legacy programs that depend on the compiler reading source records as card images.

Debug with Fx (-g)

Specifying the -g option on the command line will cause the compiler to generate symbol information for Fx. Fx is supplied with the Absoft Fortran 77 development system. Debugging Fortran applications is described in the chapter, Using the Fx Debugger.

Don’t Mangle COMMON Block Name (-N110)

The -N110 option prevents the compiler from mangling (changing) the global names for COMMON blocks. The default is to prepend the characters “_C” to the COMMON block name so that it does not conflict with other global names such as external procedure names. This option causes the compiler to emit the COMMON block name exactly as it appears in source. See also the -N25 option above.

Fortran User Guide 112 Using the Compiler

ABSOFT C/C++ OPTIONS The compiler options detailed in this section give you a great deal of control over the compilation and execution of C and C++ programs. The options fall into three general categories: Compiler Control, Compatibility, and Preprocessor.

ACC Options Figure 5-18

For quick reference, the options listed in the sections that follow are in the order in which they appear in the dialog boxes. Each option is listed with the corresponding option letter(s) and a short description. When an option is checked, the same letters will appear in the Command Line box of the ACC dialog box. Options that take arguments must have a space to separate the option from the argument. The only exceptions are the N options: they do not have a space between the option and the argument (e.g. -N18).

Optimizations (-O)

The -O option will cause most code to run faster. It includes common subexpression elimination, loop invariant removal, and strength reduction.

Source Formats

The radio buttons in the Source Formats box are used to specify the C/C++ dialect accepted by the compiler.

ARM C++ (-Tp)

C++ source conforming to the Annotated C++ Reference Manual is specified with -Tp option.

Fortran User Guide Using the Compiler 113

Draft Std C++ (-std)

Enabling the -std option allows you to use the namespaces and runtime type information features ANSI C++ in your source code.

ANSI C (-A)

Set the -A option for source which conforms to the ANSI X3.159-1989 standard for the C programming language

K and R C (-K)

The -K option is set with the radio button titled K and R C and should be used with older style Kernighan and Ritchie C. This is the default option.

COMPILER CONTROL...

When clicked, this button in the ACC dialog box displays a dialog of options for controlling various aspects of compiling the C/C++ programs. Click on the box next to the option to add the option for compiling.

These options control various aspects of the compilation process such as the level of diagnostic warning desired, the use of memory or disk for temporary files, and whether function inlining is allowed.

Compiler control dialog

Use long branches (-N18)

In certain types of unusually large program units, the 16-bit addressing capability of PowerPC branch instructions can be exceeded. In these cases, the compiler will issue a warning and the -N18 compiler option should be used to overcome the limitation. This

Fortran User Guide 114 Using the Compiler

option should only be used when the compiler issues diagnostics as it will cause more code to be generated than is usually necessary.

No inlines (-inline none)

This option prevents the compiler from inlining functions.

Use temporary files (!N61)

During compilation, the intermediate files are created to store information between passes. These files are kept in memory to reduce compilation time. If memory is limited, these files can be placed on disk by specifying the !N61 option. The names of intermediate files are generated by the Macintosh and begin with "tmp". Since these files are only useful to the compiler, they will be removed automatically at the end of the compilation process.

Profiler Information (-p)

Specifying the -p option will place profile information into a compiled program. Fx, the symbolic debugger, can then be used to gather procedure entry and timing statistucs for analysis of runtime bottlenecks. Profiling is described in detail in the chapter Using the Fx Debugger.

Procedure Trace (-N124)

Specifying the -N124 option will cause the compiler to generate code to write the name of the currently executing procedure to standard out. This option is useful for tracing program execution and quickly isolating execution problems.

Exception Handling (-except on|off)

This option enables C++ exception handling. It allows you to use the try/catch/throw constructs in your program. All functions that are called directly or indirectly from a try block must be compiled with the -except on option. Only specify this option when you are actually using exception handling, as there is a considerable overhead to its use.

Error and Diagnostic Messages

The level of diagnostic reporting can be controlled with the next seven options. The Absoft C/C++ compiler categorizes diagnostic messages as follows:

error non-recoverable syntactic error such as a missing brace or semi- colon

warning the usage or construction may be an error or non-portable, but is allowed on the assumption that you know what you are doing

informational the element is legal but may be the cause of a subtle bug

Fortran User Guide Using the Compiler 115

anachronism currently allowed construction which may not be supported in a future release

template show the point of instantiation of a template function when that instantiation caused an error

Suppress all warnings (-w31)

Checking this box suppresses the listing of all diagnostic warning messages. Various levels of warnings may be suppressed by checking the individual warning boxes as discussed below.

Suppress warnings (-w16)

Checking this box suppresses the listing of most warning messages. The only diagnostic warnings still reported are informational and anachronisms.

Suppress informationals (-w8)

This check box controls the listing of informational warning messages such as using a member name in a derived class that was defined in the base class, referencing a function which does not have a prototype, or defining a variable which is never used.

Suppress anachronisms (-w2)

Checking this box suppresses the listing of anachronism warning messages in C++ compilations such as a trailing comma in a parameter list, a temporary used for non- const reference, or the use of a count in delete[].

Suppress template warnings (-w1)

This option suppresses warnings issued when an error occurs while instantiating a template function.

Treat anachronisms as errors (-wp)

This check box causes the usage of C++ anachronisms to be treated as errors. This option should always be used when developing new code to avoid the use of deprecated features.

Treat all warnings as errors (-wabort)

This check box causes any warning condition to be treated as an error.

Max errors (-maxerr n)

This option sets the maximum number of errors that can be emitted before the compiler aborts. Setting a reasonable number, such as 20, prevents the compiler from issuing hundreds of meaningless error messages when a brace or semi-colon is missing.

Fortran User Guide 116 Using the Compiler

COMPATIBILITY…

This button displays a dialog box of options for compiling C/C++ programs. These options are designed to provide provide compatibility with various common implementations of and extensions to the C programming language.

Compatibility options dialog box Figure 5-20

Suppress Apple extensions (-appleext off)

By default, the compiler accepts the following Apple extensions to the C programming language:

• The pascal keyword is recognized and defined as an empty string.

• Pascal strings are recognized.

• C++ style comments are allowed in C programs

• The extended keyword is recognized as a long double.

The -appleext off option can be used to disable these features.

Use int enums (-enum min|int)

By default, the compiler stores enumerations in the smallest unit of memory possible. This option forces the compiler to always use an int size.

Use 68k alignment (-align mac68k|power)

This option controls the alignment of data items in structures. The default is PowerPC alignment—use the -align mac68k to override the alignment.

Fortran User Guide Using the Compiler 117

Make chars unsigned (-char signed|unsigned)

Use this option if you want the char data type to be treated as unsigned.

Munch…

When you click the Munch… button in the Compatibility… dialog box the following dialog box will be presented:

Munch options dialog box Figure 5-21

Set initialization prefix (-init prefix)

Each object module created by the compiler which contains global data items or objects that require static contruction must call an initialization routine. The -init prefix option allows you to specify the prefix given to this routine in case you are using a linker other than the one supplied by Absoft.

Set termination prefix (-term prefix)

Each object module created by the compiler which contains global data items or objects that require static destruction must call a termination routine. The -term prefix option allows you to specify the prefix given to this routine in case you are using a linker other than the one supplied by Absoft.

Fortran User Guide 118 Using the Compiler

PREPROCESSOR…

This button displays a dialog box of options for controlling the preprocessor stage of the C and C++ compilation process.

Preprocessor options dialog box Figure 5-21 Defines (-d name[=value])

Use this scrollable text box to define the names and optional values of preprocessor variables:

The -d option is used to define preprocessor variables from the command line. value can only be an integer constant. If value is not present, the variable is given the value of 1.

Undefines (-u name)

Use this scrollable text box to undefine the names preprocessor variables:

The -u option is used to undefine preprocessor variables from the command line.

Fortran User Guide Using the Compiler 119

Preprocess to file (-P)

The -P option directs the compiler to place the output of the preprocessor in a file that has the same root name as the source file and an extension of .i.

ACC -P foo.c

would produce foo.i.

Preprocess to stdout (-E)

The -E option directs the compiler to place the output of the preprocessor on stdout.

Include tree to stderr (-H)

An include file tree will be printed to stderr when the -H option is enabled.

Verbose (-v)

Enabling the -v option will cause ACC to display the commands it is sending to the compiler and linker.

Verbose templates (-ptv)

This option causes the compiler to print a message to stderr whenever a template in instantiated.

Quiet (-q)

The Absoft C/C++ compiler normally displays information to standard output (the Worksheet window) as it compiles an application. Enabling the -q option will suppress any messages printed to standard output. Errors will still be printed to the standard diagnostic output, however.

Fortran User Guide

121

CHAPTER 6

Porting Code

This chapter describes issues involved in porting FORTRAN 77 code from other platforms. One of the major design goals for Absoft Fortran 77 is to permit easy porting of FORTRAN 77 source code from mainframe computers such as VAX and IBM, and from workstations such as Sun. The result is the rich set of statements and intrinsic functions accepted by Absoft Fortran 77. The last section of this chapter describes Macintosh-specific issues about porting code.

As a general rule when porting code, use the following two compiler options:

-f Fold all symbols to lower case. -s Force all program storage to be treated as static and initialized to zero.

Ported programs that have incorrect runs or invalid results are usually caused by the differences between the Macintosh and other environments such as floating point math precision or stack-size issues. See the section Other Porting Issues later in this chapter for special considerations when porting code to the Macintosh. In addition, you may want to use this option:

-C Check array boundaries and generate better runtime errors. Using this option makes programs slightly larger and they will execute slower.

If you want to use the Absoft debugger, Fx, add the -g option to generate debugging information.

PORTING CODE FROM VAX Absoft Fortran 77 automatically supports most of the VAX FORTRAN language extensions. Below is a list of key VAX FORTRAN extensions that are supported and a list of those that are not supported. For a complete list of VAX extensions, refer to Appendix H. Using various options, the compiler can also accept VAX Tab-Format source lines and/or 132-column lines. Otherwise, only ANSI FORTRAN 77 fixed format lines are accepted.

Key Supported VAX FORTRAN Extensions

• NAMELIST—the NAMELIST terminator may be either “$” or “&” • STRUCTURE, RECORD, UNION, MAP, %FILL statements • DO WHILE loops • INCLUDE statement • ENCODE, DECODE, ACCEPT, TYPE, and most OPEN I/O specifiers • Hollerith and hexadecimal constant formats

Fortran User Guide 122 Porting Code

• “!” comments

Key Unsupported VAX FORTRAN Extensions

• Quad-precision floating point math • Absoft Fortran 77 uses IEEE floating point representation • I/O statements DELETE, DEFINE FILE, and REWRITE • Data dictionaries

Compile Time Options and Issues Absoft Fortran 77 can be made even more compatible with VAX FORTRAN by using a group of compiler options collectively referred to as the “VAX compatibility options”, listed below. When using the Commando interface for the compiler, they may be invoked by a single check box.

-f Fold all symbols to lower case. -s Force all program storage to be treated as static and initialized to zero. -N3 Include record length information for SEQUENTIAL, UNFORMATTED files. -N51 Interpret the RECL specifier as the number of 32-bit words in a record.

VAX-compatible time, date, and random number routines are available by linking with the file vmslib.o in the FLibraries folder. They are:

DATE subroutine returns current date as CHARACTER*9 IDATE subroutine returns current date as 3 INTEGER*4 TIME subroutine returns current time as CHARACTER*8 SECNDS subroutine returns seconds since midnight RAN function returns random number

The following list of VAX FORTRAN “qualifiers” shows the equivalent Absoft Fortran 77 options or procedures:

/ANALYSIS_DATA no equivalent /CHECK BOUNDS -C to check array boundaries /CHECK NONE do not use the -C option /CHECK OVERFLOW no equivalent /CHECK UNDERFLOW no equivalent /CONTINUATIONS Absoft Fortran 77 automatically accepts an unlimited number of continuation lines /CROSS_REFERENCE no equivalent /DEBUG -g to generate debugging information /D_LINES -x to compile lines with a “D” or “X” in column 1 /DIAGNOSTICS append ≥ filename to the f77 command line to create a file containing compiler warning and error messages (type Option-> for the ≥ character)

Fortran User Guide Porting Code 123

/DML no equivalent /EXTEND_SOURCE -W to permit source lines up to column 132 instead of 72 /F77 do not use the -d option /NOF77 -d for FORTRAN 66 compatible DO loops /G_FLOATING see the section Numeric Precision later in this chapter /I4 do not use the -i option /NOI4 -i for interpreting INTEGER and LOGICAL as INTEGER*2 and LOGICAL*2 /LIBRARY no equivalent /LIST a symbol table dump may be generated with the -D option /MACHINE_CODE -S to generate an assembly source file that can be assembled /OBJECT no equivalent—you can use the MPW duplicate command to copy an object file to another name /OPTIMIZE -O to use basic optimizations /PARALLEL no equivalent /SHOW no equivalent /STANDARD -N32 to generate warnings for non-ANSI FORTRAN 77 usage /WARNINGS DECLARATIONS the IMPLICIT NONE statement may be used to generate warnings for untyped data items /WARNINGS NONE -w to suppress compiler warnings

The tab size on the Macintosh may be different than the VAX. You can set the tab size for a file by pressing a-Y while editing a file and typing the tab size for the file. For more information about tab size, see the section Tab Size later in this chapter.

Runtime Issues

If the program is having problems with I/O, make sure you are using the -N3 and -N51 options described in detail in sections Use record lengths in I/O and RECL Defines 32- bit words in chapter Using the Compiler.

PORTING CODE FROM IBM VS FORTRAN Absoft Fortran 77 automatically supports most of the IBM VS FORTRAN language extensions. Below is a list of key VS FORTRAN extensions that are supported and not supported. Using a compiler option, Absoft Fortran 77 can also accept VS FORTRAN Free-Form source lines which use 80 columns, otherwise, only ANSI FORTRAN 77 fixed format lines are accepted.

Key Supported VS FORTRAN Extensions

• “*” comments in column 1 • Can mix CHARACTER and non-CHARACTER data types in COMMON blocks • The NAMELIST terminator may be an ampersand “&”

Fortran User Guide 124 Porting Code

• Hollerith constants

Key Unsupported VS FORTRAN Extensions

• Quad-precision floating point math • Absoft Fortran 77 uses IEEE floating point representation (more accurate) • Debug statements • I/O statements DELETE, REWRITE, and WAIT • INCLUDE statement syntax is different

Compile-time Options and Issues Absoft Fortran 77 can be made even more compatible with VS FORTRAN by using these compiler options:

-f Fold all symbols to lower case -s Force all program storage to be treated as static and initialized to zero -N3 Include record length information for SEQUENTIAL, UNFORMATTED files

Run-time Issues

If the program is having problems with unformatted I/O, make sure you are using the -N3 option described in detail in the chapter Using the Compiler.

PORTING CODE FROM MICROSOFT FORTRAN (PC VERSION) Absoft Fortran 77 automatically supports many of the Microsoft FORTRAN language extensions. Below is a list of key Microsoft FORTRAN extensions that are supported and not supported. Absoft Fortran 77 does not have the code size restrictions found in the segmented Microsoft FORTRAN models.

Key Supported Microsoft FORTRAN Extensions

• The NAMELIST terminator may be an ampersand “&” • The Free-Form Source Code is very similar to VS FORTRAN (-V option) • Unlimited number of continuation lines • AUTOMATIC statement • STRUCTURE, RECORD, UNION, MAP statements • SELECT CASE statements • DO WHILE loops • INCLUDE statement • OPEN statement displays standard file dialog when using FILE="" • Conditional compilation statements

Key Unsupported Microsoft FORTRAN Extensions

• Metacommands

Fortran User Guide Porting Code 125

• MS-DOS specific intrinsic functions • INTERFACE TO statement

Compile-time Options and Issues Absoft Fortran 77 can be made even more compatible with Microsoft FORTRAN by using these compiler options:

-f Fold all symbols to lower case -s Force all program storage to be treated as static and initialized to zero -N3 Include record length information for SEQUENTIAL, UNFORMATTED files

If you use the Microsoft FORTRAN I/O specifier FORM='BINARY' to read and write binary sequential files with no internal structure, do not use the -N3 option which includes record length within sequential, unformatted files. The following list of Microsoft FORTRAN metacommands shows the equivalent Absoft Fortran 77 options or procedures:

$DEBUG -C to check array boundaries and other run-time checks $DECLARE the IMPLICIT NONE statement may be used to generate warnings for untyped data items $DO66 -d for FORTRAN 66 compatible DO loops $FLOATCALLS all floating point is calculated inline or with a threaded math library in Absoft Fortran 77 $FREEFORM -V for IBM VS FORTRAN Free-Form source code $INCLUDE use the INCLUDE statement $LARGE not necessary — Absoft Fortran 77 does not have the data size restrictions found in the segmented Microsoft FORTRAN models $LINESIZE not applicable $LIST no equivalent $LOOPOPT -U for loop unrolling optimization; -R for loop invariant removal $MESSAGE no equivalent $PACK use $PACKON and $PACKOFF $PAGE not applicable $PAGESIZE not applicable $STORAGE:2 -i for interpreting INTEGER and LOGICAL as INTEGER*2 and LOGICAL*2 $STORAGE:4 do not use the -i option $STRICT -N32 to generate warnings for non-ANSI FORTRAN 77 usage $SUBTITLE not applicable $TITLE not applicable $TRUNCATE no equivalent

If code ported from MS-DOS does not compile because of many errors, the end-of-line characters within the file may not match the return character (decimal 13 or Control-M)

Fortran User Guide 126 Porting Code the Macintosh expects. To remove extraneous linefeeds from files transferred from MS- DOS which have both a linefeed and a return character, use the Replace… item in the Find menu and type control-J for the string to find and nothing for the string to replace.

PORTING CODE FROM SUN WORKSTATIONS Absoft Fortran 77 automatically supports most of the Sun FORTRAN language extensions. Below is a list of key Sun FORTRAN extensions that are supported and not supported. The Sun FORTRAN compiler appends an underscore to all external names to prevent collisions with the C library. Absoft Fortran 77, by default, does not append an underscore to maintain compatibility with the Macintosh toolbox and other MPW languages. The -N15 option may be used to append underscores to routine names.

Key Supported Sun FORTRAN Extensions

• NAMELIST; the NAMELIST terminator may be either “$” or “&” • STRUCTURE, RECORD, POINTER, UNION, MAP, %FILL statements • DO WHILE loops • INCLUDE statement • ENCODE, DECODE, ACCEPT, TYPE, and most OPEN I/O specifiers • Hollerith and hexadecimal constant formats • “!” comments in column 1

Key Unsupported Sun FORTRAN Extensions

• Quad-precision floating point math

Absoft has a compiler for Sparc-based SunOS systems. It has the same features and language extensions as Absoft Fortran 77. The compilers are 100% source-compatible.

Compile-time Options and Issues If code ported from Unix systems does not compile because of many errors, the end-of- line character within the file may not match the return character (decimal 13 or Control-J) the Macintosh expects. To change linefeed characters into carriage returns, enter the following lines in the Worksheet window:

translate " " ∂n new.f catenate old.f

Use Option-D for the ∂ character and Control-J for the .

PORTING CODE FROM THE NEXT WORKSTATION Absoft FORTRAN 77, formerly available, but now discontinued on the NextStep operating system for either Motorola or Intel microprocessors had the same optimizations and language extensions as Absoft Fortran 77. The object-oriented extensions of the

Fortran User Guide Porting Code 127

NeXT compiler are specific to the NextStep environment and are not supported with Absoft Fortran 77 for the Macintosh with PowerPC. The compilers are 100% source- compatible.

PORTING CODE FROM THE IBM RS/6000 WORKSTATION Absoft FORTRAN 77, formerly available, but now discontinued for the IBM RS/6000 computer and had the same optimizations and language extensions as Absoft Fortran 77 for Windows with Intel or PowerPC processors. The compilers are 100% source compatible.

PORTING CODE FROM INTEL 386/486/PENTIUM COMPUTERS Absoft Pro Fortran is available for the Intel Pentium systems including Windows 95, Windows 98, and Windows/NT. It has the same optimizations and language extensions as Absoft Pro Fortran for the Macintosh with PowerPC. The compilers are 100% source compatible.

PORTING CODE TO/FROM OTHER MACINTOSH SYSTEMS

Language Systems Fortran Absoft Fortran 77 and Language Systems Fortran share many extensions implemented in other compilers. In addition, Absoft Fortran 77 automatically supports most of the Language Systems Fortran specific language extensions. Below is a list of key Language Systems extensions that are supported and a list of those that are not supported. For a complete list of Language Systems extensions and their usage, refer to Appendix N.

Key Supported Language Systems Fortran Extensions

• STRING declaration statement • POINTER declaration statement • LEAVE control statement • GLOBAL, CGLOBAL, and PBLOBAL statements • CEXTERNAL and PEXTERNAL statements • INT1, INT2, INT4, and JSIZEOF intrinsic functions

Key Unsupported Language Systems Fortran Extensions

• variables in FORMAT statements • Language Systems Fortran compiler directives

Other Absoft Compilers

Fortran User Guide 128 Porting Code

Over the past 15 years, Absoft has offered several different compilers for a number of Macintosh environments. This section outlines some of the differences between these products.

MacFortran This 68000 compiler supported ANSI FORTRAN 77 and compiled programs directly from the Finder without using MPW. Although it lacked optimizations and support for many of the extensions in Absoft Pro Fortran for Macintosh with PowerPC, it compiled very fast and was easy to use.

MacFortran/020 This 68000 compiler was the same as MacFortran but it could also produce faster code for 68020 and 68030 systems that incorporated a floating point unit.

MacFortran II This 68000 compiler is very similar to Absoft Pro Fortran for Macintosh with PowerPC. It supports many of the same optimizations and extensions, but is designed for 68000 based .

OTHER PORTING ISSUES Not all porting and compatibility issues can be solved automatically by Absoft Pro Fortran or by using various option combinations. There are six issues that must be addressed on a program-by-program basis for the Macintosh computer:

Memory Management Tab Character Size Stack Issues Numeric Precision File and Path Names Floating Point Math Control

Memory Management

Fortran User Guide Porting Code 129

When an application is running on the Macintosh, there is a block of memory set aside for the application as shown in Figure 6-1. It may not be enough for large programs or ones that use extensive amounts of stack space (i.e. large local arrays).

STACK

Free Memory Total memory for an application CODE and HEAP

Simplified memory model for Macintosh applications Figure 6-1

The size of the total block of memory is defined in the SIZE resource for an application and is set automatically by the Absoft Pro linker. The linker makes this determination based on the size of the program itself, its data requirements, and an estimate of the stack requirements. The amount allocated to the stack can be adjusted with the SetPrefs tool (see THE SETPREFS TOOL section in the chapter The Macintosh Runtime Window Environment). To increase the total amount of memory allocated to the application, select the application icon from the Finder and choose the Get Info command in the File menu to display a dialog box similar to that in Figure 6-2.

Fortran User Guide 130 Porting Code

Get Info dialog for an application Figure 6-2

As a general rule, set the size to a value larger than the size of the code and data. To change the SIZE resource automatically when an application is generated, see the chapter Macintosh Programming.

Stack Issues If a program “crashes”, displays no text, shows blank menus or gives a system error such as 28, often it is caused by stack size limitations. You can get around this limitation in one of three ways:

• For applications or tools, compile with the -s compiler option to allocate all local variables in static, heap memory instead of the stack. This should solve any stack problems but it may increase the amount of memory required by the application.

Fortran User Guide Porting Code 131

• For tools, since the MPW stack is also used for tools, increasing the MPW stack will give tools more stack space. To do this, use the tool utility SetShellSize which is included as part of MPW — just type help SetShellSize in the Worksheet window and follow the instructions.

• For applications or tools, you can use the Macintosh memory calls to dynamically allocate free memory for large data structures. This is a Macintosh-specific solution. For more information, see the chapters on “Macintosh Memory Management” in Inside Macintosh.

File and Path Names Almost every operating system has a unique set of rules for valid file and path names. The Macintosh is no exception but is quite liberal in accepting special characters and spaces. File names cannot include colons (:) and must be 31 characters or less in length. Also, a filename cannot begin with a period (.). To reference a file in the folder of a running application, the file name can be used without having to specify a path as in this example with a file called data file (9 characters including the space).

OPEN(UNIT=5,FILE="data file")

Path names are the concatenation of volume names, folder names, and file names and are used to specify files in other folders. Each component of a path name is separated by a colon. A full path name always begins with the name of a volume and includes each of the folder names in the path to the file. A full path name is a complete and unambiguous identification for a file. Another type of path name is a partial path name which describes the path to a file starting from the current folder. It must begin with a colon and it is possible to specify a parent folder with a double colon.

Hierarchical folder structure of the volume MyDisk Figure 6-3

Fortran User Guide 132 Porting Code

The following two OPEN statements in the Analyzer programs open the same file as shown in Figure 6-3.

OPEN(UNIT=5,FILE="::Data:data file")

OPEN(UNIT=5,FILE="MyDisk:Data:data file")

The first uses a partial path name and, therefore, is not dependent upon the names of the volume or the folders above those referenced. The double colon (::) moves up the tree to the parent folder. The second uses a full path name which begins with the volume name (MyDisk) and traverses the hierarchical folder structure to reach the file. For more information about file, volume, and path names, see the File Manager chapter of Inside Macintosh.

You do not have to specify a filename in an OPEN statement. Use FILE="" for a standard file dialog to be displayed which prompts for a filename. For example, the following statements display these dialog boxes:

OPEN(UNIT=6,FILE="",STATUS="NEW")

OPEN(UNIT=5,FILE="",STATUS="OLD")

The FILETYPE specifier can be used with the OPEN statement to limit the selection to specific file types (see the OPEN STATEMENT section in the Input/Output and Format Specification chapter FORTRAN 77 Language Reference Manual):

OPEN(UNIT=5,FILE="",STATUS="OLD",FILETYPE="TEXT")

will limit the choices in the dialog box to just those files which have a type of “TEXT”.

Fortran User Guide Porting Code 133

Tab Character Size Absoft Pro Fortran expands each tab character in a FORTRAN source file into the equivalent number of spaces during compilation. The size of a tab character is determined from the following list in order.

• From the source file itself: All MPW document files, including FORTRAN source files, have a resource that contains the tab size for the file. It is initially set to the MPW environment variable Tab but may be changed with the Format command in the Edit menu.

• From the environment variable Tab, which is initially set to 8 spaces in the UserStartup•Fortran file, but may be changed with an MPW statement such as Set Tab 4.

• If a file does not contain a resource with the tab size and the environ- ment variable Tab is not set, the value 8 is used.

By selecting the 72 Column Window command in the Tools menu, the top-most window is given a tab size of 8.

Floating Point Math Control This section describes the basic information needed to control the IBM PowerPC Floating Point Unit (FPU) built into the Macintosh. The FPU provides a hardware implementation of the IEEE Standard For Binary Floating Point Arithmetic (ANSI/IEEE Std 754-1985). As a result it allows a large degree of program control over operating modes. Complete information on the FPU can be found in the PowerPC 601 RISC Microprocessor User's Manual. There are two aspects of FPU operation that can affect the performance of a FORTRAN program:

Rounding direction Exception handling

A single subroutine is provided with the compiler which is used to retrieve the current state of the floating point unit or establish new control conditions:

CALL fpcontrol(cmd,arg)

where: cmd is an INTEGER variable that is set to 0 to retrieve the state of the floating point unit and 1 to set it to a new state.

arg is an INTEGER variable that receives the current state of the floating point unit if cmd is 0 and passes the new state if cmd is 1.

Fortran User Guide 134 Porting Code

Rounding Direction

The first aspect of FPU operation that may affect a FORTRAN program is rounding direction. This refers to the way floating point values are rounded after completion of a floating point operation such as addition or multiplication. The four possibilities as defined in the fenv.inc include file are:

FE_TONEAREST round to nearest FE_TOWARDZERO round toward zero FE_UPWARD round toward +infinity FE_DOWNWARD round toward -infinity

Exception Handling

The second aspect of FPU operation that affects FORTRAN programs is the action taken when the FPU detects an error condition. These error conditions are called exceptions, and when one occurs the default action of the FPU is to supply an error value (either Infinity or NaN) and continue program execution. Alternatively, the FPU can be instructed to generate a floating point exception and a run time error when an exception takes place. This is known as enabling the exception. The five exceptions that can occur in a FORTRAN program with the IBM PowerPC 601 are:

FE_INEXACT inexact operation FE_DIVBYZERO divide-by-zero FE_UNDERFLOW underflow FE_OVERFLOW overflow FE_INVALID invalid argument

Fortran User Guide 135

CHAPTER 7

Building Programs

This chapter covers the specifics of building Fortran 90/95, FORTRAN 77, and C/C++ programs for the PowerPC application environment. It includes a discussion of the MPW Build and ACM commands. This chapter details the MPW tools available for advanced programming and linking using the Worksheet. The compiler, the linker, and the Fsplit utility are described. You can use each tool in the Worksheet through an MPW command: the syntax and a description of each command is listed below. To use these tools, you must have a complete understanding of the topics discussed the chapter Using the Worksheet, or have read the Macintosh Programmer’s Workshop Manual listed in the bibliography appendix.

AN OVERVIEW OF PROGRAM BUILDING There are several different ways of building an application or MPW tool with Absoft Pro Fortran. The general overview of building a completed application is as follows:

Create source files and compile them into object files with the proper interface and include files. See the section on Creating Object Files later in this chapter.

Create non-code resources with Rez and DeRez. See the section on Working with Resources in this chapter.

Create the executable program by using the linker to link object files with the necessary resources and library routines from the Toolbox. For more information on using linkers, see the section on Linking Programs, also in this chapter.

Creating MPW Tools with Absoft Pro Fortran is discussed later in this chapter.

The Components of an Application Program code, toolbox calls, library routines, and features of the Macintosh operating system and interface are all important components of an application. Output from tools such as Lnk, Link, and Make are combined with your program code to create a Macintosh application.

Macintosh applications and document files have two forks: a data fork and a resource fork, each of which contains different types of information. For PowerPC applications, the data fork contains program code. For documents and data files, the data fork contains information that is interpreted by the application that created the file. A resource fork contains information about a sequence of discrete objects called resources. When you

Fortran User Guide 136 Building Programs

create a PowerPC program in Absoft Pro Fortran, the data fork will hold the program code and the resource fork will hold information that can be used by your program.

Working with Resources A resource is one of the most important concepts in Macintosh programming. A resource is a collection of information used by the Macintosh system, such as menus, window definitions, or icons. These and other types of special information are stored in the resource fork of a program file. The application itself may use some of the resources while the Finder, or even other applications, may use the resources for getting information about the application.

Resources can be added before your program is linked using special tools and programs. A resource editor, such as ResEdit, available from Apple, provides an interactive method of modifying existing resources or copying resources between files. The MPW tool Rez, included with Absoft Pro Fortran, is a resource compiler that creates new resources based on a textual resource description file. Rez is documented in this chapter along with DeRez, a resource decompiler which generates a resource description file.

File types and creators Every program file and document file has two features: a type and a creator. The type is made up of a four-character code that classifies the file and the information it contains. For instance, when you create a program (an executable file), that file is assigned a type "APPL", representing to the system that it is an application. The creator is also a four- character code for a file, and acts as a pointer to determine which application should be launched when the file is double-clicked.

CREATING OBJECT FILES After you create and edit source files in the MPW Editor (see the chapter Using the Editor), or port files from other environments (see the chapter Porting Code), these files are compiled using the Absoft Pro Fortran compilers (described in the chapter Using the Compiler).

The compilers are invoked by using one of the commands f77, f90, or acc — these commands control both the compilers and the Lnk tool (see the section below on Linking Programs). The features of these commands simplify the process of creating finished applications, especially if you are working with a limited number of source files.

To initiate the Absoft Fortran 77 compiler from the Worksheet using one of these commands, follow these command syntax guidelines:

f90 [option…] [file…] f77 [option…] [file…] acc [option…] [file…]

Fortran User Guide Building Programs 137

where option… represents one or more of the compiler options described in chapter Using the Compiler. These options must begin with a minus sign (-); if more than one option is used, separate each option with a space. Also, some arguments appended to an individual option, such as a filename, may need to be separated from the option letter with a space.

When these commands are invoked in the Worksheet, each file will be compiled to generate an executable application or tool. The resulting application or tool will be named Link.Out by default. For example, if you enter f77 Hello.f into the Worksheet, the source code from the Hello.f file is compiled and an application will be generated in the file Link.Out. To compile Hello.f with the static local storage option, and generate a tool named Hello, enter:

f77 -s -tool -o Hello Hello.f

The option, -o name, specifies the name of the executable file overriding the default name Link.Out. The name of the file must appear after the -o option as shown above. This option is passed directly to the linker; therefore, it has no effect when used in conjunction with the -c option. In this case, a space is required between the -o and name.

Remember that the f77, f90, and acc commands are not tools. They are script files that execute the two tools that consist of the front-end and the back-end of the compiler.

If you need to create object files that are to be combined for a library, use the compiler command with the -c option. This will suppress any linking functions and an executable file will not be created, as in the following example:

f77 -c Hello.f Goodbye.f

The files are compiled into the object files Hello.f.o and Goodbye.f.o. After a source file has been compiled into an object file, it contains object code as well as any symbolic external references not known at compile time.

Since the linker is directly accessed by the compiler commands, any set of options may be passed directly to the linker. To do this, append the following option to the command:

-link opts

The argument opts is a string enclosed in quotes to be passed to the linker. For example, -link -w will pass the -w option (suppress all warning messages) to the linker.

Some other important options are listed below:

-appl Use this option to generate an application. This is the default and does not have to be specified. -tool Use this option to generate an MPW tool instead of an application.

Fortran User Guide 138 Building Programs

-plainappl Use this option to generate an application without the MRWE libraries linked. This is required when compiling a FORTRAN application that does not use MRWE, accessing the Macintosh toolbox routines directly. -g Generates debugging information for Fx, the Absoft symbolic debugger.

For a complete list of compiler options and descriptions, see Using the Compiler in this manual or type Help and the compiler name.

Fsplit - Source Code Splitting Utility When you need to manage large files, work on small portions of Fortran code, or port code from other environments, you may want to split large, cumbersome source files into one procedure per file. This can be done using the Fsplit tool. The command syntax for the tool is shown below.

Fsplit [option…] [file…] Fsplit splits FORTRAN source files into separate files with one procedure per file. The following command line will generate individual files for each procedure:

Fsplit largefile.f A procedure includes block data, function, main, program, and subroutine program declarations. The procedure,proc, is put into file proc.f with the following exceptions:

• An unnamed main program is placed in MAIN.f. • An unnamed block data subprogram is placed in a file named blockdataNNN.f, where NNN is a unique integer value for that file. An existing block data file with the same name will not be overwritten. • Newly created procedures (non-blockdata) will replace files of the same name. • File names are truncated to 14 characters.

Output files are placed into the directory in which the fsplit command was executed. The tab size is pulled from the environment variable TABSIZE if it exists, otherwise, a tab size of 8 is used. Options for the command are:

-v Verbose progress of fsplit is displayed on standard diagnostic. -V Source files are in VAX FORTRAN Tab-Format. -I Source files are in IBM VS FORTRAN Free-Form.

Fortran User Guide Building Programs 139

-8 Source files are in Fortran 90/95 Free Source Form. -W Source files are in wide format.

Ftnchek - ANSI Compliance Utility When source programs are designed to run on a variety of different computers, perhaps compiled with different compilers, it is important to minimize the use of features which are not part of the established definition of the language. Ftnchek (FORTRAN checker) is a useful tool for identifying the use of these features as well as locating semantic errors — FORTRAN language usage which is legal within the syntax definitions, but is wasteful or may cause incorrect operation. Complete documentation for Ftnchek can be found in the file ftnchek.doc.

Ftnchek [option…] [file…]

In the following list of options, the default setting is listed in parentheses after the description.

-[no]calltree print subprogram call tree. (nocalltree) -[no]crossref print call cross-reference list. (nocrossref) -[no]declare list undeclared variables. (nodeclare) -[no]division catch possible divide by 0. (nodivision) -[no]extern check if externals defined. (extern) -[no]f77 warn of nonstandard constructs. (nof77) -[no]help print help screen. (nohelp) -[no]hollerith warn about holleriths under -port. (hollerith) -[no]library treat next files as library. (nolibrary) -[no]list print program listing. (nolist) -[no]novice extra help for novices. (novice) -[no]portability portability problems check. (noportability) -[no]pretty warn of deceiving appearances. (pretty) -[no]project create project file. (noproject) -[no]pure functions have no side effects. (pure) -[no]reference print who-calls-who reference list. (noreference) -[no]sixchar catch non-unique names. (nosixchar) -[no]sort prerequisite-order sort of modules. (nosort) -[no]symtab print symbol table info. (nosymtab) -[no]truncation check for truncation pitfalls. (truncation )

Fortran User Guide 140 Building Programs

-[no]verbose verbose output. (verbose) -[no]volatile assume volatile common blocks. (novolatile) -include=str include-file directory. (NONE) -output=str output file name. (NONE) -arguments=dd check subprogram arguments where: (3) 0=no checking 1=check number of arguments 2=check type of arguments 3=check number and type of arguments -array=dd check subprogram array arguments where: (3) 0=no checking 1=check number of dimensions 2=check type of array 3=check number of dimensions and type of array -columns=dd maximum line length processed. (72) -common=dd COMMON block checking where:. (3) 0=no checking 1=check data type of variable 2=check size of variable 3=check data type and size of variable -usage=dd variable usage where: (3) 0=no checking 1=check if variable is used before it is defined 2=check if variable is declared but never used 3=check both 1 and 2 -wordsize=dd standard word size in bytes. (4) -wrap=dd width of page to wrap error messages. (79)

Note: Ftnchek is most useful on source files that do not make use of any of the extensions to the FORTRAN programming language incorporated by the Absoft compiler.

LINKING PROGRAMS FOR POWERPC

Fortran User Guide Building Programs 141

Linking programs is the process of combining a group of object files into an application, desk accessory, driver, or MPW tool. The result is a new executable file. The Absoft tool that provides this feature is the Lnk tool, or otherwise called the Linker. This tool is also used to create libraries (see the section Creating Libraries for PowerPC for details).

The Lnk tool links these object files into an application or tool called the output file. The Linker creates (or replaces) program code and places the object files as linked segments into the data fork of the output file. The linker then assigns the new application a type (by default ‘APPL’ for application) and a creator (‘????’). The default output file name is Link.Out — this name can be changed with the -o option.

If you use one of the compiler commands f77, f90, or acc with the -c option to create an ordinary object file only, it contains object code and symbolic references to global variables and identifiers unknown at compile time. If you execute one of these commands without the -c option, the Lnk command is automatically invoked, creating the executable file.

The format for the Lnk command is:

Lnk [option…] [file…]

The options for the Lnk command are:

-o name Specifies the name of the executable file instead of the default Link.Out. name must appear after the -o option. -main name Specifies the name entry point of the application. The default is __start. -T addr Specifies the base address of the code (or text) section. -D addr Specifies the base address of the data section. -d Suppresses warnings for duplicate symbols definitions in code and data. -ac nn Use this option to align the code section to an nn byte boundary. The value of nn must be a power of 2. This option is always set with nn equal to 16 when a compiler invokes the linker. -ad nn Use this option to align the data section to an nn byte boundary. The value of nn must be a power of 2. This option is always set with nn equal to 16 when a compiler invokes the linker. -export name

Fortran User Guide 142 Building Programs

This option is used when creating shared libraries. See the section Creating Libraries for PowerPC for details. -O Use this option to direct the linker to organize your subprograms in such a way that the shortest possible procedure references are taken to minimize page faults and/or cache inconsistencies. -xm library This option specifies that a static library is to be created. See the section Creating Libraries for PowerPC for details. -xm sharedLibrary This option specifies that a shared library is to be created. See the section Creating Libraries for PowerPC for details. -sym (on|off) This option controls the output of the auxiliary symbol file. See the Linker Options paragraph in the Debugging section of the chapter Macintosh Programming for more information. -w Suppresses all warning messages. -d Suppresses duplicate symbol warning messages only. -fast (on|off) This option controls whether memory or disk files are used to store linker information. The default is -fast on and indicates to use memory. -dead (on|off) This option controls whether the linker removes unreferenced routines and data. The default is -dead on and indicates to remove dead code and data. -map name Use this option to specify the name of the file to write a location map. -p Use this option to display progress information to diagnostic output. -t type Sets the file type to type. The default type is 'APPL'. -c creator Sets the file creator to creator. The default creator is '????'. -aliases name This option is used to specify the name of the file containing aliases for global symbol names. -domunch This option inserts code to call static constructors and destructors for C++ classes when using the Absoft C/C++ compiler. -savecfrg

Fortran User Guide Building Programs 143

This option directs the linker to leave the applications cfrg resource unchanged. -saveSIZE This option directs the linker to leave the applications SIZE resource unchanged. -pack (on|off) Packs data consistent with the Apple pidata format. The default is on. -expand (on|off) -expand on implicitly sets -pack off and supplies explicit zeros in the data fork for the bss section. -weak : This option specifies that the imported from is weak. For more information on weak loader symbol binding, consult Inside Macintosh: PowerPC System Software. -modlib [+][-][!][~] This option sets flags in the executable file which direct the loading of import libraries specified by . + and - specify the current version and the implementation version of the import library, respectively. ! specifies that the library has init priority. ~ specifies that the library is weak. The options must be given in the order presented. For more information on import libraries, consult Inside Macintosh: PowerPC System Software. -share This option indicates whether the data section of an application can be shared with other applications. must be one of the following: 0 never share 1 context share (default) 2 task share 3 team share 4 global share

For more information on the PEF format, consult PEF—PowerPC Executable Format Reference Specification.

BUILDING PROGRAMS Building a program describes the process of compiling and linking a program into an executable file. The f90, f77, or acc commands, or the Compile and Compile and Launch commands are ideal for compiling and linking a small number of source files. However,

Fortran User Guide 144 Building Programs

when there are many source files or when source files are in mixed languages, such as Fortran 90/95 and the C programming language, these commands become impractical to use. Working with a large number of source files or files from different languages requires that you can easily tell how they are compiled. When you use the build commands discussed below, these commands work with a special text file called a makefile.

A makefile is a text file that contains a list of source files and rules. The list includes the object files and how they are combined, along with the variable names and comments from the object files. The makefile describes the dependencies between each source file in the program and contains a set of commands for building up-to-date files.

Creating Makefiles

When you use the Create Build Commands… from the Tools menu, or the ACM command from the Worksheet, MPW automatically creates a makefile containing a list of the commands needed to compile and link an application, tool, or desk accessory. You also have the option of creating makefiles from scratch, using the MPW scripting features described in the MPW Reference Manuals. However, the easiest way to create a makefile is to use the Tools menu or the ACM command from the MPW worksheet.

After a makefile is created with the Tools menu commands, it can be modified at any time to help manage the compilation of numerous source files. Since the makefile is generated as a text file, it can be opened in a text window and changed as the program grows in size or complexity.

To create a makefile, choose the Create Build Commands… command in the Tools menu, and select the source files that will be included in the final program. The menu item Create Build Commands… is also available as an MPW command, ACM, and can be used directly from the Worksheet.

Modifying Makefiles As source files, resources and libraries are added to a program, you may need to modify some parts of the makefile. For example, you may need to append additional compiler or link options to a file.

Format of a Makefile

In order to modify a makefile, you need to know the various types of information that the makefile contains. Basically, the makefile contains information about the separate pieces of a program and about the commands used to link and compile it.

The target file is the program or executable file that is to be built, or any file with prerequisite files. A target file is dependent on certain components to run; these are the prerequisite files and the rules that connect the files.

Fortran User Guide Building Programs 145

The prerequisite files are the source files, library files and resources on which a target file is based. When these files are modified, the target file must be rebuilt. A target's prerequisites may, in turn, be targets with their own prerequisites.

The dependency rules are the rules that connect all prerequisite files to a target file, and include the commands needed to build the target.

A root is a top-level source file, which is not a prerequisite of any other file. A makefile can contain one or more roots. Variable definitions and comment lines are also included in a makefile.

Create Build Commands

When you choose the Create Build Commands… from the Tools menu, the following dialog appears:

Figure 7-1 ACM dialog

This dialog operates in exactly the same manner as the Compile dialog described in detail in the chapter Using the Compiler.

FORTRAN 77 files used in makefiles must end with a .f extension, Fortran 90/95 in a .f90 extension, and C/C++ in a .c or .cpp, respectively. Many of the options in the ACM dialog box may be ignored.

Fortran User Guide 146 Building Programs

ACM Command

The ACM command is an implementation of the Create Build Commands… item in the Tools menu. When this command is issued, the makefile program.make is created — the parameter program will be the name of the program. The makefile includes the source and library files needed by the program.

The format of the ACM command is:

ACM [-o program] [-O] [-FORTRAN] [-sym on] [-plainappl | -tool | -mrwe | -library | sharedLibrary] [-ci dir] [-fi dir] [-c creator]`[-export file] program file…

-o program Specifies the name of the output file. This is a required option. -O Specifies compiler optimizations. -FORTRAN Indicates that the main program of this application or tool is written in FORTRAN. This option does not appear in commando dialog. -sym on Creates build commands that construct an object containing symbolic debugger information for Fx. -plainappl Creates build commands for building a stand-alone, desk-top application. -tool Creates an MPW tool, discussed in this chapter. -mrwe Creates an MRWE Application, a stand-alone, desk-top application, linked with the Macintosh Runtime Window Environment (MRWE) for standard output and input. This is the default and does not have to be specified. -library Creates an XCOFF static library. See the section Creating Libraries for PowerPC later in this chapter for details. -sharedLibrary Creates a PEF shared library. See the section Creating Libraries for PowerPC later in this chapter for details. -ci dir Adds dir to the C/C++ include paths. -fi dir Adds dir to the FORTRAN include paths.

Fortran User Guide Building Programs 147

-c creator The creator can be optionally provided when building an application. -export file This option specifies that PEF shared library should export the names in file. See the section Creating Libraries for PowerPC later in this chapter for details.

Build (aB)

The Build… command builds a program, using those source files that have been modified since you last built the program. When selected a dialog box will prompt you to type in the name of the program.

Figure 7-2 Dialog box for build

When you click the OK button, the program will be built. A new makefile will be automatically created that shows the dependencies between the source files and the commands needed to build the program. Before the application is built, MPW will automatically save any windows and other status information.

BuildProgram command

BuildProgram is implemented as the Build… menu item in the Tools menu. The command builds the program with a transcript of the build including timing information and commands used to do the build, and writes this information to standard output. The command and options are passed directly to the Make tool, which will then build the program with the existing makefile. If a makefile does not exist for the program, the default makefile name Make.file is used. If an error occurs in the build process, the status value is returned. The syntax for the command is:

BuildProgram program [option]

The -e option can be specified to completely rebuild everything, regardless of dates or temporary files. Other Make options can be used as well.

Make Command

The Make command generates the commands needed to build up-to-date versions of the specified target files. The Make tool reads a makefile created by the ACM command, and determines which components of the program need to be rebuilt. The Make script then rebuilds only those components of a program necessary. The command syntax of Make is:

Fortran User Guide 148 Building Programs

Make [ option…] [targetFile…] Options for the makefile are as follows:

-d name [=value] Define a variable name with the given value. This variable defined from the command line takes precedence over the same variable in the makefile. -e Rebuild everything regardless of dates. The program is rebuilt, ignoring any other up-to-date object files or other temporary files that exist. -f makefile Read dependency information from makefile. More than one -f option can be specified; all information is treated as if it were contained in a single file. -p Write progress to diagnostic output. -s Show structure of dependencies. A dependency graph will be written for the targets to the standard output, indentation will indicate levels in the dependency tree. This option will override the normal Make output.

Fortran User Guide Building Programs 149

The Snowflake program This tutorial will guide you through the steps required for creating a makefile and building an executable file for the sample file Snowflake. Although there are many steps, it is actually a very simple process.

What to do How to do it

Make the {FExamples} directory the Select the…Examples:FExamples: current directory. from the Directory menu.

Execute Create BuildCommands. Select the command Create Build Commands… in the Tools menu.

Name the executable file. Type “Snowflake” in the Program Name box.

Select the two source files that are Click the Source Files… button and needed for the Snowflake example. then double-click on each of the One file contains the FORTRAN Snowflake.f and Snowflake.r files. source code and the other has Click on the Done button. resource information.

Add the ColorPickerLib shared library. Click the Libraries… button and then OtherLibraries... Navigate to the MPW Libraries:SharedLibraries folder. Click on All Libraries and add ColorPickerLib.

Create the makefile. Click the ACM button or press the Enter key. The name of the makefile is Snowflake.make.

Select the makefile to build the Select Build… from the Tools Snowflake example. directory and type “Snowflake” in the Program Name box.

Compiler and linker options cannot be selected directly when building a program using this method. To use compiler options, the makefile must be edited as follows:

What to do How to do it

Change the makefile for Snowflake Edit the file Snowflake.make and to compile with basic optimizations. change the line near the top of the file from FFLAGS= to FFLAGS="-W".

Fortran User Guide 150 Building Programs

CREATING LIBRARIES FOR POWERPC Macintosh PowerPC based computers support two types of libraries: static and dynamic. A static library is a collection of object files (modules), each containing one or more routines, that are maintained in a single file — a library. When a library file is presented to the linker, modules that are required to satisfy unresolved external references are selected for inclusion into the application file. The advantage of a library is that only those modules that are required to satisfy unresolved external references are linked into the application. The FORTRAN 77 runtime libraries, libfmath.o and libfio.o, are examples of static libraries. Not every FORTRAN 77 program requires a hyperbolic tangent function, so it is only linked into those programs that require it. A dynamic library is similar to a static library in that it contains a collection of routines in object modules. The difference is that the elements of the library are not linked into the final application file, but rather are available for linking when the application is executed. The advantage to this type of library is that the individual applications can be smaller and several applications can share the same library. The disadvantage is that the dynamic or shared library must be available on every computer where the application is to be run.

Note: Dynamic or shared libraries are not supported with CabonLib applications that link against mrwe.o or any ProFortran I/O library.

The Lnk command, introduced earlier, is used to create static library files by combining multiple object files into a single library file with type 'OBJ' (this is the type generated by f77 with the -c option). The Lnk command is also used to create dynamic libraries. The syntax of the Lnk command when used to create library files is:

Lnk [option…] [file…]

-o name Specifies the name of the executable file instead of the default Link.Out. name must appear after the -o option. The output of Lnk is logically equivalent to the concatenation of the input files. -export name This option, used in conjunction with the -xm sharedLibrary option, specifies the filename of a file containing the module names to be exported in the shared library. When used in conjuction with the -xm library option, this option specifies the filename of a file that contains all of the exportable names in the library. -xm library This option specifies that a static library is to be created. -xm sharedLibrary This option specifies that a shared library is to be created. See the -export name option described above.

Fortran User Guide Building Programs 151

-p Use this option to display progress information to the diagnostic output. -w Suppresses all warning messages. -curver This option sets the current version in the import library. For more information on import libraries and version checking, consult Inside Macintosh: PowerPC System Software. -defver This option sets the definition version in the import library. For more information on import libraries and version checking, consult Inside Macintosh: PowerPC System Software. -impver This option sets the implementation version in the import library. For more information on import libraries and version checking, consult Inside Macintosh: PowerPC System Software.

Shared libraries have a default type of “shlb” and a default creator of “cfmg”. They must be placed in the Extensions folder of the System Folder in order for applications that use the procedures in them to find the library.

WORKING WITH RESOURCES During program development, you may need to work with the resource tools in MPW, Rez and DeRez. DeRez is the resource decompiler, it creates a resource description file, a text file that can be modified and changed. This file is compiled by the Rez tool into a finished resource file.

Rez can also combine multiple resource files into a single resource file, delete and modify resources, and append resources to an application file that was created with the Lnk tool. This next example, from the Snowflake.make file, compiles the resource description file and appends it to the application Snowflake.

Rez -rd Snowflake.r -o Snowflake -append The format to invoke the Rez tool from the worksheet is:

Rez [option…] [file…]

Rez compiles a source file called a resource description file that describes resources using text commands. The format of a resource description file is similar to the output from the DeRez tool. Options for the Rez tool include:

Fortran User Guide 152 Building Programs

-o name Use this option to specify the name of the output file instead of the default Rez.Out. name must appear after the -o option as shown in the example below. -append This option causes Rez to append resources to the output file rather than replacing existing ones. -t type Sets the file type to type. The default type is 'APPL'. -c creator Sets the file creator to creator. The default creator is '????'. -p Use this option to display progress information to diagnostic output. -rd Suppresses all warning messages if a resource type is redeclared.

For a complete list of DeRez options type Help DeRez or see the Macintosh Programmer's Workshop Manual. See the bibliography in Appendix D for information.

The syntax to invoke the DeRez tool is as follows:

DeRez [option…] file [resourceDescriptionFile…]

DeRez is very useful for taking existing resources from applications so that they can be modified and then recompiled with Rez. Each resourceDescriptionFile can contain declarations for specific resources such as the standard Macintosh resources described in {RIncludes}Types.r and {RIncludes}SysTypes.r. Some options for the DeRez command are listed below.

-only type [(ID1[:ID2])] This option causes DeRez to read only the resources of the type and ID specified. The option may be used repeatedly to specify more types. Type is a quoted resource type such as 'MENU' and ID1 and ID2 specify a range of resource ID numbers. The entire option parameter must be quoted if an ID or ID range is specified. -only type The type in this form of the -only option does not need to be quoted, but does not provide choosing specific IDs.

Fortran User Guide Building Programs 153

-skip type [(ID1[:ID2])] With syntax identical to the two forms of the -only option above, this option excludes the specified resources. The option may be used repeatedly to exclude more types. -p Use this option to display progress information to diagnostic output.

For a complete list of DeRez options type Help DeRez or see the Macintosh Programmer's Workshop Manual. See the bibliography in Appendix D for information.

The following example decompiles the MENU resources of the application Hello in the FExamples folder and displays the textual representation to standard output. The Types.r resource description file is read from the {RIncludes} folder.

DeRez -only MENU "{FExamples}"Hello Types.r

Include Files

Every resource description file must include the file Types.r which defines standard Macintosh resources. It is located in the RIncludes folder. The following line placed in column one at the top of a resource description file will do this.

#include "Types.r"

More specialized resources are in the RIncludes folder.

Adding an Icon to an Application A few resources must be added to an application for the Finder to correctly display a unique icon for an application instead of the default application icon. The following example defines the ICN#, BNDL, and FREF resources. The resource FSMP can have any name but must match the creator that is set with the -c type linker option. See the chapter “Finder Interface” in Inside Macintosh for details about how these resources are used by the Finder. This code is from the Snowflake.r file in the FExamples folder.

data 'FSMP' (0) { $"24 53 61 6D 70 6C 65 20 46 37 37 20 41 70 70 6C" $"69 63 61 74 69 6F 6E 20 2D 20 56 65 72 73 69 6F" $"6E 20 31 2E 30" };

Fortran User Guide 154 Building Programs

resource 'ICN#' (128) { { /* array: 2 elements */ /* [1] */ $"00 00 00 00 70 EF CE 0E 49 28 2A EA 46 2B AA AA" $"50 AA AA AA 59 AB AA AA 56 A8 2A AA 50 AB CA AA" $"50 AA 0B 1A 50 AA 08 42 70 EE 0F BE 00 00 00 00" $"00 00 00 00 7F FF FF FE 40 00 00 02 47 EF F7 FA" $"47 EF F7 FA 46 00 30 1A 46 00 60 32 47 80 C0 62" $"47 81 80 C2 46 03 01 82 46 06 03 02 46 0C 06 02" $"46 0C 06 02 46 0C 06 02 40 00 00 02 7F FF FF FE", /* [2] */ $"00 00 00 00 70 EF CE 0E 79 EF EE EE 7F EF EE EE" $"7F EE EE EE 7F EF EE EE 76 EF EE EE 70 EF CE EE" $"70 EE 0F FE 70 EE 0F FE 70 EE 0F BE 00 00 00 00" $"00 00 00 00 7F FF FF FE 7F FF FF FE 7F FF FF FE" $"7F FF FF FE 7F FF FF FE 7F FF FF FE 7F FF FF FE" $"7F FF FF FE 7F FF FF FE 7F FF FF FE 7F FF FF FE" $"7F FF FF FE 7F FF FF FE 7F FF FF FE 7F FF FF FE" } };

resource 'BNDL' (128) { 'FSMP',

{ /* array TypeArray: 2 elements */ /* [1] */ 'ICN#', { /* array IDArray: 1 elements */ /* [1] */ 128 }, /* [2] */ 'FREF', { /* array IDArray: 1 elements */ /* [1] */ 128 } } };

resource 'FREF' (128) { 'APPL',

"" }; An icon, other than the default application icon, can be added to applications that use the Macintosh Runtime Window Environment (MRWE) by adding these resources to the MRWE.r file and rebuilding the MRWE library as described in the Read Me file of the MRWE folder.

Fortran User Guide Building Programs 155

All applications that use MRWE have the following for its icon when shown in the Finder:

The help is simply defined in a ‘hfdr’ resource with ID -5696. This code is from the MRWE.r file in the FExamples:MRWE folder:

resource 'hfdr' (-5696) { HelpMgrVersion, hmDefaultOptions, 0, 0, { HMStringItem { "This application was developed using the Absoft " "Fortran 77 globally optimizing compiler." } } };

The SIZE(-1) Resource When an application is launched, the SIZE resource with an ID of -1, if any, is examined to determine how much memory the application requires. The SIZE(-1) resource from the file Snowflake.r is shown below and sets the minimum memory size to 48K and the preferred to 64K. These are the values that appear in the Get Info… dialog box from the Finder. The other elements of the SIZE(-1) resource are documented in the Event Manager chapter of Inside Macintosh, (volume VI) listed in Appendix D.

Fortran User Guide 156 Building Programs

resource 'SIZE' (-1) { dontSaveScreen, acceptSuspendResumeEvents, enableOptionSwitch, canBackground, /* We can background */ multiFinderAware, /* We do our own activate/deactivate */ backgroundAndForeground, /* Not a background-only application */ dontGetFrontClicks, /* Don’t get click event on activate */ ignoreChildDiedEvents, not32BitCompatible, /* Not for 32-bit address space */ reserved, reserved, reserved, reserved, reserved, reserved, reserved, * 64, /* Preferred size, 64K */ * 48 /* Minimum size, 48K */ };

The SIZE(-1) resource may be modified for applications that use MRWE by editing the MRWE.r file and rebuilding the MRWE library as described in the Read Me file of the MRWE folder. By default, MRWE has a SIZE(-1) resource that specifies 384K for the minimum and preferred sizes for applications. This value may be increased for large applications that need more memory when using MultiFinder.

The minimum size can also be set from the Get Info… dialog. The change will be lost, however, the next time the application is recompiled.

CREATING A TOOL USING ABSOFT PRO FORTRAN In addition to generating a double-clickable application with Absoft Pro Fortran, any program can also be compiled as an MPW tool that uses the Worksheet window, or any other window, for standard input and output. Although generating an application is recommended for most programmers, there are advantages and disadvantages for generating a tool.

Advantages of generating a tool

A compiled program executing as a tool runs within MPW. This means faster program start-up since the Finder does not have to handle another application.

Standard output (FORTRAN preconnected units 5, 6, 9, and *) is displayed on the front-most window and can be saved and edited like all windows.

A tool can access some run time features such as command line arguments and environment variables from the MPW environment as described in the optional Macintosh Programmer's Workshop Manuals.

Fortran User Guide Building Programs 157

Disadvantages of generating a tool

A tool requires MPW to execute. This is not a problem during program development or for single-machine installations but can limit its use as a completed program.

Memory use of a program is restricted to that available within MPW. Stack size limitations can cause problems when static storage is not used. See the section Memory Management later in this chapter for more details.

The easiest way to generate a tool is to select the MPW Tool option in the Output File box of the Pro Fortran compiler Commando dialog as in the figure below.

Commando dialog for building an MPW tool Figure 7-3

There is a similar -tool option for the ACM command. It is the MPW linker, invoked automatically when compiling, that determines if a tool or an application is to be generated. This section will explain other details such as initialization, linking, and memory management.

Fortran User Guide 158 Building Programs

Tool Initialization This section about tool initialization applies only to those programmers that are calling the Macintosh toolbox directly as described in the chapter Macintosh Programming. Since tools created with Absoft Pro Fortran are executed within the MPW environment, many Macintosh toolbox routines have already been initialized. The following calls should not be made:

ExitToShell MaxApplZone InitDialogs RsrcZoneInit InitFonts SetApplLimit InitMenus SetGrowZone InitResources TEInit InitWindows

Memory Management When a program is executing as a tool, it must share memory space with MPW itself. This means that large tools may not even load. In such a case, the program should be compiled and launched as an application.

Another issue for tools is stack size. Problems with the stack when running a compiled program as a tool show up as system errors that may crash the machine. Getting system errors 28, 2, and 3 may indicate stack problems. When do compiled programs use the stack? Non-static local variables are allocated space on the stack at the beginning of the program unit in which they are defined. All local variables in Fortran 90/95 and FORTRAN 77 can be made static, thus avoiding this problem, by using the -s option for static storage when compiling or by using SAVE statements to force static storage. Note that programs using recursion, may no longer work with static storage.

If a compiled program cannot use static storage and must be executed as a tool, there is one solution that changes the stack size for MPW itself. You can increase the MPW stack size by using the SetShellSize tool. For detailed information, refer to the Macintosh Programmer's Workshop Manual.

Fortran User Guide 159

CHAPTER 8

The Macintosh Runtime Window Environment

This chapter discusses the Macintosh Runtime Window Environment (MRWE), a special feature of Absoft Pro Fortran which gives your Fortran 90/95, FORTRAN 77, and C/C++ programs a Macintosh interface with windows and menus. Usually, when you want to create applications with windows and menus, you need to know how to use the Macintosh Toolbox and the Apple user-interface guidelines. When you create an application using MRWE, your program will automatically exhibit these features without the need for intensive Macintosh programming. MRWE is convenient and flexible to use.

MRWE applications are created using the Apple Macintosh Carbon library. This allows your applications to have the look and feel of the classic Macintosh interface when running on an operating system such as OS 9. When the applications are moved to OS X, they will have the look and feel of that operating system running in the native environment.

USING MRWE MRWE is a collection of pre-compiled Fortran routines contained in the library file MRWE.o that you can link with your program. Applications generated by Absoft Pro Fortran are usually linked with this library unless you build a tool or explicitly select an Application without MRWE as shown in the dialog box below. The Fortran source code for MRWE is in the FExamples folder and can be used as an example of how to call Macintosh toolbox routines.

Fortran User Guide 160 The Macintosh Runtime Window Environment

The Compile dialog allows you to select the format of the executable file. An executable setting of Application (the default) will cause your program to be built as a stand-alone, double-clickable application with MRWE providing a window and menus interface. If your source code includes its own event loop and calls Toolbox routines, you should disable MRWE by choosing Application without MRWE for the executable file. [Note: You cannot use MRWE when creating an MPW Tool.]

The MRWE Window When you launch a program that has been linked with the MRWE library, you will see a blank window on the screen and, above it, a menu bar, as shown below. This window is where MRWE displays standard output from Fortran programs and is where all standard input is typed. It looks like a terminal display, but allows you to see text that has scrolled off the screen.

The Macintosh Runtime Window Environment Figure 8-2

Standard input and output are preconnected to the Fortran I/O units 5, 6, 9 and *. Any of these except * may be connected instead to a file by specifying the unit in an OPEN statement. After closing the file on that unit, the unit will be reconnected to standard input and output.

Fortran User Guide The Macintosh Runtime Window Environment 161

How Your Program And MRWE Work Together When your program is launched, control is first passed to MRWE, which sets up a Macintosh environment with menus and a window. After the window appears, the application begins executing your Fortran program. By default, your program is the only program active; other programs are suspended and MRWE is inactive until an I/O statement occurs. You cannot pull down menus, terminate the application, or use other applications at this point. Your Macintosh is completely dedicated to executing your Fortran program at maximum speed. During any input and output statements (i.e. READ, WRITE, ENCODE, etc.), you can either terminate the application with a Command-Period (a-.) or switch to other applications. When the program is waiting for you to type standard input, you also have complete control of the menus and normal mouse actions. If you want the ability to terminate your application while it is calculating, or want to run other applications, select the -N9 compiler option before compiling the program.

The -N9 compiler option turns on the timer interval feature. Your program will be interrupted at timed intervals to check for Command-Period termination and to allow other programs enough time to run smoothly. The default interval is one-half second, which can be changed with the SetPrefs tool discussed later in this chapter.

Without the Timer Interval option activated, switching between applications and Command-Period checking will still occur, but only during Fortran input and output statements. If you are not running other programs at the same time this will not create a problem, but if you are, the other programs may appear sluggish.

If you did not include the -N9 compiler option when compiling, and your program is executing lengthy calculations that you want to stop, you can regain control by using the Force Quit feature of and above. First press the Control-Option-Command keys and then the Escape key. A dialog box will appear on the screen allowing you to immediately stop program execution. Make sure the correct application is indicated in the dialog box message. If it is not, click on the Cancel button and repeat the above procedure. If your application is indicated, click on the Force Quit button, and your Macintosh should return to the Finder. [Caution: Data in files that were open may be lost during this procedure and it may be wise to restart the computer after you regain control.]

Force Quit Feature of System 7 Figure 8-3

Fortran User Guide 162 The Macintosh Runtime Window Environment

Working With Text in MRWE The MRWE window operates a little differently from text windows in MPW. The window that appears is named after the application (truncated to 24 characters) with “ output” appended. Text can be entered from the keyboard, but unlike MPW windows, you can end the line using either the Return or Enter key.

You can only type into the window when a READ statement is currently active for standard input (i.e. one of the preconnected units), and you can only type on the last line of the window. Any text that was already in the window when the READ statement began cannot be modified. You can, however, copy any text in the window to the clipboard. Also, when using the extended keyboard, the Home, End, Page Up, and Page Down keys can be used for scrolling. To insert an end-of-file character, type either Command-Return or Command-Enter.

All output characters, except for the bell character (ASCII 7), are displayed in the window. This means that ASCII control characters such as a backspace (ASCII 8) will be displayed according to the current font, usually as a small box. Tab characters (ASCII 9) are not expanded into spaces but will be expanded if the text is saved and the file is opened as an MPW document.

The MRWE window has a text limit of 30K. When this limit is reached, the oldest text in the window is automatically deleted to make room for new output. See the section entitled The SetPrefs Tool for information about automatically saving text.

Using THE MRWE Default Menus An MRWE application automatically has several menus built-in. Following is a description of the commands performed by each item within these default menus.

File Menu

The File menu contains commands for saving and printing the text in the window.

Save (aS)

This command saves the MRWE text to an MPW document file — a text file. The window title is used for the file name, and if the file already exists, it is overwritten. The window title is the name of the application with the word “ output” appended. To automatically save the window text when the program ends, see The SetPrefs Tool section later in this chapter.

Fortran User Guide The Macintosh Runtime Window Environment 163

Save As…

This command saves the window text to an MPW document file — a text file. It displays a standard file dialog prompting for a file name in which to save the text. The default file name is the name of the application (truncated to 24 characters) with “ output” appended. If the file already exists, you will be prompted to overwrite it.

Page Setup…

Choosing this command displays the standard page setup dialog box for the printer. To change printers, use the Chooser in the Apple menu.

Print Window…(aP)

To print the contents of the window to the printer, use this menu item. A dialog box is displayed showing the printing status. When a block of text is selected, this menu item changes to Print Selection… and prints just the selected text rather than the entire window. Note that multiple copies cannot be printed on an ImageWriter in draft mode.

Quit (aQ)

This command stops execution of the application by executing a STOP statement, thus closing all open Fortran units. Edit Menu

The Edit menu contains the standard editing commands for cutting, pasting, and copying text.

Undo (aZ)

This command is always disabled unless a desk accessory is being used.

Cut (aX)

This command removes the selected text in the window and places it on the Clipboard. Text on the Clipboard may be pasted into other applications. Like other editing commands, this command is only available during a READ statement, and any text that was already in the window before the READ statement began cannot be cut.

Copy (aC)

The Copy command places the selected text from the window onto the Clipboard and leaves the text of the window unchanged. Text on the Clipboard may be pasted into other applications.

Fortran User Guide 164 The Macintosh Runtime Window Environment

Paste (aV)

This command replaces the selected text of the window with the text on the Clipboard. If no text is selected in the window, the Clipboard text is inserted at the insertion point. Like other editing commands, this command is only available during a READ statement, and any text that was already in the window before the READ statement began cannot be pasted into.

Clear

This command clears the selected text. Like other editing commands, this command is only available during a READ statement.

Font and Size Menus

The font and the size menus list available fonts and font sizes. They allow you to change the appearance of text in a window to improve viewing. A checkmark beside an item in these menus shows the current setting for the frontmost window.

PROGRAMMING WITH MRWE The sections that follow discuss features of MRWE that improve your program’s user interface and allow it to communicate with other programs. Menus can be easily customized and messages can be sent to other programs. Before discussing these features, a better understanding of the differences between a typical Macintosh application and a typical Fortran program is necessary.

Program Organization: Fortran VS. Macintosh Usually a program has the following structure: first, it initializes its variables, possibly reading data from files, then it calculates, then it outputs the results. Some of these steps may be repeated, but the basic order of execution is linear (see figure 8-4 below). Once a program begins, there is typically very little interaction with the user.

Fortran User Guide The Macintosh Runtime Window Environment 165

Initialization, including menus

Initialization Ask Macintosh and Operating data System for the input next event pending

Event Calculate Loop Keypress

Mouse-click Dispatch the AppleEvent event Write Other out results

Typical Fortran Program Typical Macintosh Program Figure 8-4 Figure 8-5

The Macintosh, on the other hand, presents a very different, highly interactive environment to the user. The interface provided on a Macintosh between the program and the user allows for control and data selections to be made in a graphical manner as well as the more traditional textual methods. The Macintosh communicates user requests to the program through a mechanism known as an event that describes an action such as making a menu selection, clicking the mouse button, or typing a key on the keyboard. After the program receives an event it processes it, carrying out whatever action is required.

These actions are usually directed by an event loop, in which the program requests from the Macintosh any events pending for the program, carries out the directed action, and then repeats the process (see figure 8-5). When no events are pending, the program will carry out whatever other procedures it was designed to do. Some programs may simply be idle at this stage if they are designed entirely to react to user input (such as a drawing program).

Unfortunately, there is much more to Macintosh programming than this simple description implies, and it would be necessary to add a great deal of programming to even the simplest Fortran program to add a Macintosh look and feel to it. MRWE can add most of these features to your program and provides facilities that allow you to add additional features without delving into the details of Macintosh programming.

Fortran User Guide 166 The Macintosh Runtime Window Environment

MRWE Event Loop Operation

As the preceding discussion indicates, an event loop is a necessary component of a Macintosh program, and one is built into the MRWE routines. To use it, you must provide subprograms that this event loop can call to respond to user requests. This section will describe how to use this built-in event loop.

Just one call to the subroutine mrwe_EventLoop will begin this mechanism, making your program behave automatically in response to user actions.

EXTERNAL recur,term CALL mrwe_EventLoop(recur,term)

where: recur is the name of a routine that will be called repeatedly while the event loop executes. This routine should execute quickly and return so that the program remains responsive to the user. Specify zero if you do not want to use a recurrent routine.

term is the name of a routine that you want to call when the program terminates. Specify zero if you do not want to use a termination routine.

When using these routines, remember to declare them as external in the subprogram in which mrwe_EventLoop is called. After calling mrwe_EventLoop, all events will be processed appropriately and, if a menu item is chosen, the subprogram you have associated with it will be called. Before making this call, you will probably want to set up menu items and tell MRWE which routine will respond to particular menu items. This process will be explained in the next section on Customizing Menus.

Note that mrwe_EventLoop never returns to the procedure from which it was called. It loops endlessly, processing the events sent by the user. Your program will only end when one of the following occurs: the user chooses to quit, one of your menu response routines issues a STOP statement, or there is a runtime error. [Caution: mrwe_EventLoop must not be called more than once.]

Fortran User Guide The Macintosh Runtime Window Environment 167

Customizing Menus This section describes how to customize menus to suit your application. Menus and menu items can be added, deleted, or modified easily using MRWE.

Adding Menus

Menus can be added to your program at any time, but if you call mrwe_EventLoop you should probably install some menus and items first. This is because after calling mrwe_EventLoop, the user will control most of what the program does next. To install a menu item, call the function mrwe_AddMenu specifying the menu name, the item name, and the name of the menu response routine that should be called when the item is chosen:

INTEGER*4 mrwe_AddMenu EXTERNAL Routine itemID = mrwe_AddMenu(menuName,itemName,Routine)

where: menuName is a CHARACTER expression that specifies the menu that the item will appear in. If the menu does not already appear in the menu bar, it will be created and will appear to the right of the other menus.

itemName is a CHARACTER expression that specifies the name of the item to be added to the bottom of the menu. If the item already exists, then only the Routine can be changed.

Routine is the name of the menu response routine to be called when the item is chosen, and should be declared external in the routine from which mrwe_AddMenu is called.

itemID, the function result, is an INTEGER*4 value. If an error occurs, itemID is -1; otherwise, it is a value that uniquely identifies the menu item. The itemID is a composite of the menu number and item number. If an EQUIVALENCE is done of itemID to an array of two INTEGER*2 elements, the first element is the menu number and the second element is the item number.

Fortran User Guide 168 The Macintosh Runtime Window Environment

Special Characters

Certain characters have special meanings in menu item names. If you specify any of the characters listed below when creating the item, you must include those characters in exactly the same order when referring to the item by name.

Character Meaning < When followed by the letters B, I, U, O, or S, sets the style of a menu item to bold, italic, underline, outline, or shadow, respectively. / When followed by a character, invokes the item from the keyboard by pressing the command key and the character together. ( Disables the menu item. This is not recommended—instead, see “Enabling/Disabling Menu Items” later in this section. ! When followed by a character, puts that character to the left of the item; also, see “Adding Checkmarks to Menus” later in this section. - Makes the item a line separator when it is the first character in the menu item name; typically used as (- to disable the separator.

Special Characters in Menu Item Names Table 8-1

Menus and the READ statement

The menu items that you install in the menu bar by calling mrwe_AddMenu will be available to a user of your program after your program calls mrwe_EventLoop and as soon as your menu response routines have finished responding to any menu items that have been chosen. The user will also be able to pull down the menus while your program is in the middle of executing a READ statement on standard input (units *, 5, 6, or 9), but the menu items will be disabled. This is because menu response routines must not execute Fortran I/O statements while the program is in the middle of a READ statement on Standard Input.

If you know that your menu response routine and every routine that it calls does not execute any Fortran I/O statements, you can enable the menu item even during a READ on Standard Input. To do this, add a @ character to the beginning of the name of the menu item when you install it with mrwe_AddMenu.

Fortran User Guide The Macintosh Runtime Window Environment 169

Removing a Menu or Menu Item

To remove a menu item or an entire menu, use the function mrwe_RemoveMenu:

INTEGER mrwe_RemoveMenu iresult = mrwe_RemoveMenu(itemID)

where: itemID is an INTEGER*4 expression that specifies the item to be removed from the specified menu. It is the same value that was returned by mrwe_AddMenu when the item was first installed. If you specify 0 for the item component of itemID, the entire menu will be removed.

iresult is an INTEGER. The function will return a value of 0 if successful, or -1 if there was an error.

Important: When a menu item is removed, any items that come after it will be given new item numbers. For example, in a menu with four items: if item #2 is removed, then item #3 becomes item #2, and item #4 becomes item #3. Any variable containing an itemID for an item after the one removed will no longer indicate the proper item. Note also that while item numbers are renumbered when an item is removed, menu numbers do not change when a menu is removed.

Menu Response Routines and mrwe_DoMenu

When you choose a menu item while running an MRWE application, the routine that performs that function (the “response routine”) is executed. This type of routine should be declared as:

INTEGER FUNCTION Routine(itemID) INTEGER*4 itemID

where: itemID is the same value that was returned by mrwe_AddMenu when the item was first installed. This value can be helpful if more than one item uses the same response routine.

Your response routine is called by the function mrwe_DoMenu, which is normally called by mrwe_DoMouseDown whenever a mouse-down event occurs with the cursor in the menu bar at the top of the screen. The mrwe_DoMenu function can also be called explicitly at any time during the program when you want to execute the routine associated with a menu command. The mrwe_DoMenu routine will return one of the following two results: the result of the response routine, or -1 if the item could not be found. Call the mrwe_DoMenu function as follows:

INTEGER mrwe_DoMenu iresult = mrwe_DoMenu(itemID)

Fortran User Guide 170 The Macintosh Runtime Window Environment

where: itemID is an INTEGER expression. It is the same value that was returned by mrwe_AddMenu when the item was first installed. It is a composite of the menu and item numbers.

iresult is the INTEGER returned by the response routine mrwe_DoMenu called. If you declare your response routines as functions, they can return a value through mrwe_DoMenu. If you declare them as subroutines, you can call mrwe_DoMenu as a subroutine.

Adding Checkmarks to Menus

Checkmarks can be placed beside a menu item after it is created by calling the routine mrwe_MenuItemCheckmark:

CALL mrwe_MenuItemCheckmark (itemID,state)

where: itemID is an INTEGER*4 expression that specifies the menu item where the checkmark will be placed. It is the same value that was returned by mrwe_AddMenu when the menu item was installed. state, is a LOGICAL expression. If state =.TRUE., a checkmark will be placed next to the item; if state =.FALSE., the checkmark will be removed.

Enabling/Disabling Menu Items

The function mrwe_MenuItemEnable is used to enable or disable a menu item:

INTEGER mrwe_MenuItemEnable iresult = mrwe_MenuItemEnable(itemID,state)

where: itemID is an INTEGER*4 expression that specifies the menu item which will be enabled or disabled. It is the same value that was returned by mrwe_AddMenu when the item was first installed. state is a LOGICAL expression. If the state = .TRUE., the menu item will be enabled; if state = .FALSE., the item will be disabled.

iresult is an INTEGER. The function will return a value of 0 if successful, or -1 if there was an error.

When installing an item by calling mrwe_AddMenu, you can also disable it by adding the special character ( before the item name. However, this method will not work correctly with the mrwe_MenuItemEnable function and is not recommended. Instead, install the item as enabled, and then explicitly disable it using mrwe_MenuItemEnable.

Fortran User Guide The Macintosh Runtime Window Environment 171

Further Information About Menus

For further information on menu features, see Inside Macintosh I, “The Menu Manager”. To access these features, use the menu number and item number in the itemID returned by mrwe_AddMenu. If the routine expects a MenuHandle, this INTEGER*4 value can be derived using the function GetMHandle, passing to it the menu number as a VAL2():

RECORD /ItemID/ sdItem ! defined in the file MRWE.inc EXTERNAL DefaultSettings INTEGER*4 h_menu

sdItem.both=mrwe_AddMenu('Settings','Use Defaults',DefaultSettings) h_menu = GetMHandle(VAL2(sdItem.menu)) CALL SetItemMark(VAL4(h_menu), VAL2(sdItem.item),VAL1(‘•’))

Launching OTHER APPLICATIONS From your Fortran program you can launch other Macintosh applications using the function mrwe_LaunchApp as defined below. You can also make an application that is already running become the front-most, active application. [Note: This function can only be used with System 7.]

INTEGER mrwe_LaunchApp iresult=mrwe_LaunchApp (name,front,useMin)

where: name is a CHARACTER expression that specifies the application to be launched and can be expressed in one of the following three ways:

1) process=programName Identifies the application to be launched; specify the path if necessary. 2) creator=XXXX Launches an application using its creator type. However, if there is more than one program with the same creator type, the system will launch the first one it finds. 3) self Allows an MRWE application to refer to itself. You can use this to bring your program to the front (see example below).

Fortran User Guide 172 The Macintosh Runtime Window Environment

front is a LOGICAL expression that determines whether the specified application should be the frontmost application. If front=.TRUE., the application will become the frontmost application. If the application is not currently running, it will be launched in front of all other applications. If the application is already running, it will become the frontmost application. If front=.FALSE., the position of the application will remain unchanged. The menu bar at the top of the screen shows the menus of the frontmost application. useMin is a LOGICAL expression that refers to the amount of memory needed to run the program. If useMin=.TRUE., then the program will be launched if the minimum amount of memory specified is available. If useMin=.FALSE., then the program is launched only if the preferred amount is available in the system. These values can be viewed and changed in the Finder by selecting the application’s icon and choosing Get Info in the File menu. If the program is already running, useMin will be ignored.

iresult is an INTEGER error code indicating problems that may prevent launching the application. (See Table 8-6 later in this chapter for a list of error codes.)

The following statement shows how to launch ResEdit:

CALL mrwe_LaunchApp('creator=RSED',.TRUE.,.FALSE.)

ResEdit is specified by using its creator ID 'RSED'. The value of front is .TRUE., so the program is launched in front of all other running applications. Because useMin = .FALSE., ResEdit will only be launched if the preferred amount of memory is available.

The next example shows how to make your Fortran program the frontmost application: CALL mrwe_LaunchApp('self',.TRUE.,.FALSE.)

Apple Events Apple Events is a System 7 feature that allows Macintosh applications to communicate with each other. By using this feature, you can have your applications send messages to and receive messages from other applications. MRWE allows you to use both the standard messages defined by Apple Computer and to define your own messages. This section will describe how these events (or messages) are classified, what information you must specify to transmit an event successfully, and examples of how to send and receive various events.

Fortran User Guide The Macintosh Runtime Window Environment 173

Apple Event Target

The application to which you send an Apple Event is called the target and is specified similarly to the way name is specified when launching an application (see “Launching Other Applications” above):

Target Specification Description

process=programName Sends the message to the application whose name is specified; include the path if necessary. creator=XXXX Sends the message to an application whose Creator ID is specified. sender Sends the message to the application that sent the last Apple Event received by your application. browser Shows the Browser dialog box, allowing the user at runtime to select any currently running application to send the Apple Event to. browser=prompt Shows the Browser dialog box with a custom prompt message instead of Choose a program to link to:. self Sends a message to itself. same Sends an event to the same target to which the most recent event was sent.

Target Specification for Apple Events Table 8-2

Apple Event Class and ID

The class and ID of an event indicate the action to be carried out—what the sender wants the target application to do. The class is a category of events that perform related functions. For example, Finder events make the Finder perform specific tasks such as restarting or shutting down the computer. The class and eventID arguments are specified with CHARACTER*4 values. For Finder events, the class is indicated by the abbreviation FNDR. The event ID identifies the specific event being sent, such as “rest” for restart. (See Table 8-4 later in this section for a list of common Apple Events).

Extra Information in an Apple Event

Some Apple Events require additional information in order to complete a message. For example, an Open Document or Print Document event must specify which document to act on; this is called extra information. Events can be classified according to the kind of extra information required, if any. The following table shows the three kinds of extra information supported by MRWE and how they are represented as INTEGER values.

Fortran User Guide 174 The Macintosh Runtime Window Environment

Kind Value Description

signal 0 A signal event needs no extra information. It signals a request to do something or indicates that something has been done. For example, an application can tell another application to quit. document 1 A document event operates on a document. The name of the document being operated on must be specified. For example, one application can tell another application to print a document. text 2 A text event includes a character string. Two MRWE applications can pass information back and forth using text events.

Kind of Extra Information for an Apple Event Table 8-3

Typical Apple Events

Apple Computer has defined many Apple Events and has specified the class, event ID, and kind of extra information associated with each event. An application that supports the Apple Events feature can send or receive at least four basic events called Required Apple Events: Open Application, Open Document, Print Document, and Quit Application. MRWE supports some of the standard Apple Events and also allows you to define your own events. It allows you to send these events to other programs and to specify routines that will respond if one of these events is received by your application (see Receiving Apple Events later in this section). Required Apple Events is a subset of the Core class of Apple Events—the latter is identified by the abbreviation “aevt”.

Following is a table of common Apple Events, their class, event ID, and extra information specifications, and a brief description of what they do.

Fortran User Guide The Macintosh Runtime Window Environment 175

Event name Class Event Kind of What the event does ID extra info

Open Document aevt odoc document Tells the target application to open the specified document.†

Print Document aevt pdoc document Tells the target application to print the specified document.†

Open aevt oapp signal Tells the receiving application it has just Application been opened; usually causes an untitled document to appear.†

Quit Application aevt quit signal Tells the receiving application to begin the process of quitting.

Do Script misc dosc text Tells an application to perform actions specified in a scripting language, such as MPW’s or HyperCard’s (see “Scripting” later in this chapter).

Restart FNDR rest signal Tells the Macintosh to restart.*

Shutdown FNDR shut signal Tells the Macintosh to shut down.*

Sleep FNDR slep signal On a portable Macintosh, puts the computer in low-power mode.*

Empty Trash FNDR empt signal Tells the Finder to empty the trash.*

About aevt abou signal Tells the Finder to show its “About This Macintosh” window.*

Show Clipboard FNDR shcl signal Tells the Finder to show its clipboard window.*

† When an application is first launched, it will immediately receive one of these three events. Open Application is only sent when neither Open Document nor Print Document will be sent upon launch. When MRWE launches an application, it automatically sends an Open Application event.

* These Apple Events only work if sent to the Finder on the Macintosh running the application. Also, they all work the same as the corresponding Finder menu items.

Common Apple Event Specifications Table 8-4

Sending Apple Events

An Apple Event can be sent from one application to another as follows:

INTEGER mrwe_SendAE iresult=mrwe_SendAE(class,eventID,extraKind,target,extraInfo)

Fortran User Guide 176 The Macintosh Runtime Window Environment

where: class, a CHARACTER*4 expression, is a category of related events, such as FNDR for Finder events.

eventID, a CHARACTER*4 expression, identifies which event to send, such as 'odoc' for an Open Document event or 'quit' for a Quit Application event.

extraKind, an INTEGER, specifies the kind of extra information, if any, that needs to be sent along with the event. Its value can be 0 for a signal event, 1 for a document event, or 2 for a text event.

target, a CHARACTER expression, identifies the application that the event is sent to.

extraInfo, a CHARACTER expression, is the extra information needed for certain kinds of Apple Events.

iresult is an INTEGER error code indicating problems that may occur while sending the event, such as an inability to send the event or the target application’s inability to receive the event properly. (See Table 8-6 for a list of error codes.)

For example, you could send an Apple Event from an MRWE application to any application which understands Apple Events, and tell it to print a certain text file. To have your program tell Microsoft Word™ to print the document called results, you would use the following statement:

ires = mrwe_SendAE('aevt','pdoc',1,'creator=MSWD','results') It only takes one function call to send an event. The first argument identifies the target application (Microsoft Word), the second and third arguments define the class and event ID, and the fourth and fifth arguments indicate that the event is a document event and specify the name of the file.

Receiving Apple Events

MRWE provides a mechanism for receiving Apple Events, but it is up to you to determine how your program will react when it receives a event. When using Apple Events, you must specify routines that respond to particular events, just as you would specify a response routine when adding menu items (see “Customizing Menus” earlier in this chapter). For example, you may write one routine to respond to Open Document events and another to respond to Print Document events. You need to tell MRWE which events you want to respond to and the name of the routine that will handle the event. You do this by installing an Apple Event response routine using the function mrwe_AddAppleEvent.

Fortran User Guide The Macintosh Runtime Window Environment 177

LOGICAL mrwe_AddAppleEvent EXTERNAL Routine lresult=mrwe_AddAppleEvent(class,eventID,extraKind,Routine)

where: class, a CHARACTER*4 expression, identifies the category of the event to be received.

eventID, a CHARACTER*4 expression, identifies which event within the class will be received, such as 'odoc' for an Open Document event or 'quit' for a Quit Application event.

extraKind, an INTEGER, specifies the kind of extra information, if any, that will be received along with the event. Its value can be 0 for a signal event, 1 for a document event, or 2 for a text event.

Routine is the name of the response routine MRWE will call when the event is received, and should be declared external in the routine from which mrwe_AddAppleEvent is called.

lresult is a LOGICAL value indicating whether the response routine was installed. If lresult=.TRUE., the routine was installed properly. If lresult=.FALSE., the response was not installed because Apple Events are not supported by .

For example, a routine that handles Print Document events could be installed with the following call, where PrintDoc is the name of a function that will be called every time the application receives a Print Document event.

lres = mrwe_AddAppleEvent('aevt', 'pdoc', 1, PrintDoc) Response routines should be declared like this for signal events:

INTEGER FUNCTION Routine(class,eventID) CHARACTER class*4, eventID*4 or like this for a response routine that responds to document or text Apple Events:

INTEGER FUNCTION Routine(class,eventID,extraInfo) CHARACTER class*4, eventID*4, extraInfo*(*)

For a document event, extraInfo is the path and filename of the document to act on. For a text event, it is a text string. The INTEGER value that your function should return is an error code. It should return 0 if everything went well, or one of the error codes shown in Table 8-6 to indicate to the sender that a problem occurred while responding to the event. There is one response routine that is built into MRWE to handle Quit Application events, called mrwe_QuitAE. Normally, there should be no need to change this routine.

When your application is launched by the Finder under System 7, the Finder will send either an Open Application event, an Open Document event, or a Print Document event.

Fortran User Guide 178 The Macintosh Runtime Window Environment

The following table shows several methods you can use to launch an application and the corresponding Apple Event your application will receive:

Method of launch Apple Events received

Double-click the application icon or single- An Open Application event. click it and choose Open from the File menu.

Double-click a document icon. An Open Document event, if successful. The creator of the document must match that of the application (Mrwe by default). Also, if there is more than one application with the same creator, the application that is launched may not be the one you expect.

Select the application icon and the icons of An Open Document event for each document one or more documents, then double click on whose creator matches the application’s creator. any selected icon or choose Open in the File menu.

Select the icons of one or more documents, An Open Document event for each document. then drag them to the application icon.

Select the application icon and the icons of A Print Document event for each document whose one or more documents, then choose Print in creator matches the application’s creator. the File menu. Immediately after the Print Document events, a Quit Application event will be received.

Launch the application from another Probably an Open Application event, although it application, like MPW. depends on the application doing the launch.

Apple Events Received Upon Launch Table 8-5

Fortran User Guide The Macintosh Runtime Window Environment 179

Error Codes Returned from Apple Event Routines

Apple Event routines return an INTEGER error code. If the value returned is 0, no error occurred; if it is not 0, an error occurred either in sending the Apple Event, or in the target application receiving the event. Following is a list of error codes and their meanings:

Error code Meaning

0 No error occurred in either sending or receiving the event.

-108 Not enough memory available to complete the action. If sending an Apple Event to an application that is not currently running, the preferred amount of memory is not available in which to launch it.

-128 The user of the application pressed Cancel in the Browser dialog.

-1701 The wrong kind was specified for an Apple Event, or the extra information in the event could not be extracted properly.

-1712 No response from the target application within the limit of seven seconds.

-1717 No handler installed to handle Apple Events of that class and eventID. Handlers should be installed before the call to mrwe_EventLoop is made.

-5553 The operating system does not support the requested feature. For example, System 6 does not support either Apple Events or using mrwe_LaunchApp to launch other applications.

Error Codes for Apple Events Table 8-6 Other Examples of Apple Events

Following are some additional examples of common events you might wish to transmit between applications:

Sending a request to the Finder

If you are running lengthy processes overnight or over the weekend, you may want to turn off your machine after all processes are completed. To do this, simply send the Finder a Shut Down Apple Event. This will turn off the computer if the Shut Down item in the Finder's Special menu can turn off the system. When sending an Apple Event to the Finder, you must properly specify the path of the System Folder that contains the Finder. For example, if your hard disk is named “HD”, you could send a Shut Down event with the following statement:

Fortran User Guide 180 The Macintosh Runtime Window Environment

ires = mrwe_SendAE('FNDR','shut',0,'process=HD:System Folder:Finder','')

Fortran User Guide The Macintosh Runtime Window Environment 181

Using other standard Apple Events

To cause another application (which supports Apple Events) to open a particular file, you would send that application an Open Document event specifying the file:

ires = mrwe_SendAE('aevt','odoc',1,'creator=MSWD','test') To allow your application to respond to Open Document events, install a response routine to handle Open Document events:

ires = mrwe_AddAppleEvent('aevt','odoc',1,OpenDocProc)

Sending information between MRWE applications

One application could send a document event to another application telling it to process the file in a certain way. When the second application finishes, it can send a signal event back to the sender to indicate completion.

Another way to send messages is through text events. The class and eventID are not limited to the examples shown in Table 8-4 earlier in this section. They can be defined as any four characters you choose to distinguish different events. Following is an example of how to send information through text events. The sending application would include:

CHARACTER*30 internalFile WRITE (internalFile,*) a,b,c ires=mrwe_SendAE('mrwe','guas',2,'process=SecondApp',internalFile) and the receiving application would include:

EXTERNAL GuasProc . ires=mrwe_AddAppleEvent('mrwe','guas',2,GausProc) . END . INTEGER FUNCTION GausProc(class,type,internalFile) CHARACTER*4 class,type CHARACTER*(*) internalFile . READ (internalFile,*) a,b,c Scripting

Scripting refers to text commands that an application can interpret and execute. MPW and HyperCard have scripting languages, but they do not accept the same text commands. An Apple Event called Do Script sends text commands from one application to another that has a scripting language, allowing the scriptable application to be controlled. It is not enough for an application to have a scripting language; it must also accept the Do Script Apple Event. HyperCard 2.1 and MPW 3.3 are the first versions of these applications that support Do Script. An example of sending a scripting command to HyperCard is:

Fortran User Guide 182 The Macintosh Runtime Window Environment

ires = mrwe_SendAE('misc','dosc',2,'creator=WILD','Answer "Press ' & 'OK to flash the screen." with "Flash" '//CHAR(13)//'Flash')

Further Information About Apple Events

MRWE supports sending and receiving only certain kinds of Apple Events. This is because the information carried in an Apple Event can be very diverse and complex. Some programs may use Apple Events to carry information in a form MRWE cannot recognize. To learn more about Apple Events, consult Inside Macintosh VI , “Apple Events Manager” (Chapter 6), and the Apple Events Registry, published by Apple Computer, Inc.

Creating Multiple Windows You can easily open additional windows in MRWE. While the standard window described at the beginning of this chapter shows characters in the standard input and output units, additional windows can show characters written to other units. By specifying ACCESS="window" in an OPEN statement, you open a window connected to the unit specified in the OPEN statement. Any read or write functions associated with that unit will appear in a window. The ACCESS specifier can be expressed in the following three ways: ACCESS="window"

ACCESS="window, height, width"

ACCESS="window, height, width, top_edge, left_edge"

where: height and width define the dimensions of the window in pixels (not including the title bar of the window). Both arguments should be expressed as positive integers.

top_edge and left_edge define the distance in pixels from the top of the screen to the top of the window and from the left edge of the screen to the left edge of the window, respectively. Both arguments are expressed as signed integers (either positive or negative).

The following is a simple example of how to use the OPEN statement to create an additional window in an MRWE application:

OPEN (7,FILE='Second Window',ACCESS='window, 200, 360')

WRITE (7,*) 'This text will appear in the second window'

READ (7,*) ! This is like a PAUSE statement, but in the new window

CLOSE (7) The first line creates a window titled 'Second Window' and connects it to unit 7. The size will be 200 pixels tall and 360 pixels wide. Since the location of the window is not specified, the window will open using the MRWE default for window location. The

Fortran User Guide The Macintosh Runtime Window Environment 183

second line writes the statement to the window. The READ statement in the third line will function like a PAUSE statement and wait for the user to press the Return or Enter key. When either key is pressed, the program will continue to the fourth line, which will close the window.

Showing Alert Messages Macintosh applications often announce messages when a problem occurs by showing an Alert dialog box:

Show Alert Box Example Figure 8-6

To show an Alert dialog box, use:

CALL mrwe_ShowAlert(button,message)

where: button is an INTEGER whose value indicates the contents of the button that dismisses the Alert.

message is a CHARACTER string containing the text of the message to be displayed.

Following are the possible values of the button argument and the corresponding buttons that will appear in the dialog box:

Value Button 0 Ok 1 Cancel 2 Continue

3 Quit (causes the program to stop)

4 Ok (widens the dialog box by 15 percent)

“Show Alert” Buttons Table 8-7

Fortran User Guide 184 The Macintosh Runtime Window Environment

The SetPrefs Tool The MRWE interface to your Fortran program can be easily customized to meet your needs. The runtime attributes that you can specify include text characteristics, memory requirements, and how the application behaves when it quits. Included with Absoft Fortran 90/95 is the MPW tool SetPrefs, which lets you set preferences for runtime behavior. Like other MPW tools, SetPrefs can be used either through a Commando dialog box (see figure 8-7) or from the Worksheet command line. An example of invoking SetPrefs from the Worksheet command line follows:

SetPrefs Link.out -pause -sizemin 1000

Executing this command line will cause the MRWE application Link.out to perform a Fortran PAUSE statement before it quits and will set its minimum memory requirement to 1000 kilobytes.

To access SetPrefs using the Commando interface, enter:

SetPrefs… (Note: Press Option-; to display …)

The following dialog box will appear:

SetPrefs Dialog Box Figure 8-7

Below is a brief description of the options that are available to you within the SetPrefs Tool. Options are grouped according to the way they appear in the SetPrefs dialog box and are followed by the appropriate command line arguments.

Fortran User Guide The Macintosh Runtime Window Environment 185

Applications to affect

Before you can choose any customization options in the dialog box, you must identify the applications whose attributes will be affected. You can select either all future applications, or one or more specific applications.

All future applications ({AbsoftLibraries}MRWE.o)

Check this box if you want to change the MRWE.o library; so that any future applications linked with MRWE will have the new attributes you have selected.

Select Applications… (ApplicationNames)

Click on this button to open a file selection dialog box that allows you to choose one or more applications. The attributes that you select will apply to these applications when you click the Setprefs button.

End of execution

These options control the actions of the MRWE window before the application stops executing.

Pause (-pause)

Click the checkbox if you want MRWE to pause after the program ends, allowing you to read output in the window. By default, MRWE immediately quits.

Save Text (-saveOnClose never|prompt|always)

When MRWE quits, text in the window can be saved. If this option is never, text will not be saved. If this option is prompt, a dialog will ask whether text should be saved. To automatically save text without a prompt, use always.

Window characteristics

These options affect only the standard MRWE window, not windows opened with the ACCESS=“window” specifier in an OPEN statement.

Window name (-savename name)

This is the name used in the title bar of the window. By default, it is the name of the application (often called Link.out) with the suffix ' output'.

Close box (-closebox)

Click the checkbox to give the MRWE window a close box. If the window has a close box, clicking it causes the program to stop.

Fortran User Guide 186 The Macintosh Runtime Window Environment

Window Size (-windowsize normal|maximize)

When MRWE starts, this specifies the size of the window. If the normal is selected, the window is the default size. If maximize is selected, the window is maximized.

Text characteristics

These options control the appearance of text characters in the window. You may prefer a text style different than the default for easier reading. Also, the text style of the window controls the text style when you print from MRWE.

Tab Size (-tabsize size)

This is the tab modulo size MRWE. If the value is greater than 20 or less than 0, the value is the default, 8. If the value is 0, tabs are passed as is to the application.

Font (-font fontname)

This specifies the font to be used in the window; the default font is Monaco.

Font Size (-fsize fontsize)

Type in a font size in points or select one from the pop-up menu; the default is 9.

Line Space (-linespace points)

This option defines the amount of space between lines in points; the default is 0.

No Font Menus (-nofontmenus)

Click the checkbox to use Font and Size menus in the application; the default state is on.

Memory requirements

These options set the application’s memory requirements, which are shown in the Get Info dialog box in the Finder.

Preferred (-sizepref KiloBytes)

Number of kilobytes of memory the program initially asks the system for. In the Finder's Get Info dialog box, this is the “Suggested size” and will initially be used for the “Current size”, although you can change this.

Fortran User Guide The Macintosh Runtime Window Environment 187

Minimum (-sizemin KiloBytes)

This is the minimum number of kilobytes required to run the application. The application will not be launched if this minimum amount of memory is not available.

Timer interval

If you turn on the timer interval feature with the -N9 compiler option, your program will be interrupted at timed intervals to check for Command-Period termination and to allow other programs enough time to run smoothly.

Timer (-timer 60ths-of-a-second)

The timer interval is expressed as the number of 60ths of a second that MRWE will let Fortran code process exclusively. After the interval has expired, MRWE will allocate processing time to other active programs. By default, the interval is set at 30 (1/2 second).

File characteristics

All Macintosh files have two attributes identifying the application that created the file and the type or format of information contained in the file. When you save the text in an MRWE window, it is saved by default as if MPW had created the file and the file contains standard text. In some cases, you may want the file to have a different creator or type. These two options let you specify either or both of these attributes. [Note: These attributes only apply to saving text from MRWE, not to files opened with a Fortran OPEN statement.]

Creator (-creator 4-chars)

Specify four characters to identify the application that created the file(s) saved from MRWE. By default, this is MPS which indicates MPW.

Type (-type 4-chars)

Specify four characters to identify the type of file saved from MRWE. By default, the type is TEXT which can be read by MPW and applications such as word processors or SimpleText.

Fortran User Guide

189

CHAPTER 9

Macintosh Programming

This chapter covers the broad topic of programming specifically for the Macintosh and covers additional topics of interest such as interfacing Absoft Pro Fortran with other languages, calling Macintosh toolbox routines, and debugging.

Where appropriate, sample Fortran programs in the FExamples folder are referenced. You can make it the current folder by selecting the FExamples folder in the Directory menu or by entering the following line in the Worksheet:

Directory "{MPW}"Examples:FExamples

Most of the examples may be compiled by simply opening the source file, selecting the command line for compiling as shown in Figure 9-1, and then pressing the Enter key. All standard output and diagnostic output when compiling the examples are routed to the Worksheet.

Selection of the command to compile an example Figure 9-1

To execute a compiled application or tool, type the name on a line in the Worksheet and press Enter or launch an application by double-clicking its icon from the Finder.

Fortran User Guide 190 Macintosh Programming

USING THE MACINTOSH TOOLBOX This section describes how to access the routines available in the Classic and the Carbon Libraries of the Macintosh toolbox. Not all Classic routines are available with the Carbon Library and many operations must be performed differently. In particular, with the Carbon Library you must use “accessor” functions to manipulate system data structures; you can no longer access the components directly. For a complete explanation of the entire Macintosh toolbox, refer to Inside Macintosh listed in the bibliography. Written by Apple, Inside Macintosh is the definitive resource for Macintosh programming and is essential if you plan to use the toolbox directly.

The following short Fortran 90/95 example shows how to use the Macintosh toolbox. It draws a diagonal line and then an oval inside of a box frame in the current window. Code from this example will be used throughout this section to demonstrate various issues.

PROGRAM Sample

USE WINDOWS

TYPE (Rect) :: r TYPE( WindowRecord) :: front POINTER(p_front, front)

p_front = FrontWindow() CALL SetPort(p_front)

CALL MoveTo(0_2, 0_2) ! x = 0 y = 0 CALL LineTo(50_2, 25_2) ! x = 50 y = 25

r%top = 25 r%left = 50 r%bottom = 75 r%right = 150 CALL FrameRect(r) CALL PaintOval(r)

PAUSE END

This example uses Fortran 90/95 derived types. The TYPE statements declare the rectangle type r and the window type front. The actual types are defined in the include files. The PAUSE statement keeps the graphics from disappearing at the end of the program.

The same example in FORTRAN 77:

GLOBAL DEFINE INCLUDE "Windows.inc" END

PROGRAM Sample

RECORD /Rect/ r RECORD /WindowRecord/ front

Fortran User Guide Macintosh Programming 191

POINTER(p_front, front)

p_front = FrontWindow() CALL SetPort(VAL4(p_front)) ! or CALL SetPort(front)

CALL MoveTo(VAL2(0), VAL2(0)) ! x = 0 y = 0 CALL LineTo(VAL2(50), VAL2(25)) ! x = 50 y = 25

r.top = 25 r.left = 50 r.bottom = 75 r.right = 150 CALL FrameRect(r) CALL PaintOval(r)

PAUSE END

This example uses two special features of Absoft Fortran 77. First, GLOBAL DEFINE allows STRUCTURE, PARAMETER, INLINE, and EXTERNAL definitions from the INCLUDE files to apply to all program units within a source file, reducing compile time because the files are read only once. Second, the RECORD statement declares a rectangle structure r and a window structure front. The actual structures are defined in the include files. The PAUSE statement keeps the graphics from disappearing at the end of the program.

How Absoft Fortran 90/95 Interfaces with the Toolbox

A group of Fortran 90/95 include files with the file extension .inc allows Absoft Fortran 90/95 to interface with the Macintosh toolbox. These files contain Fortran 90/95 declarations for every routine and most of the structures, types, and constants defined in Inside Macintosh, volumes I to VI. The files are named after the Macintosh managers to which they refer; they are the same as the chapter titles in Inside Macintosh. The include files for Fortran 90/95 have been implemented as modules. Quickdraw.inc contains source code for the module QUICKDRAW.

All of the include files have been pre-compiled. For each .inc file there exists a corresponding .mod file that contains the compiled module code. To use QUICKDRAW.mod, pass the compiler the -macModFiles option, and employ the following statement:

USE QUICKDRAW

This USE statement will define all the Quickdraw information for a single program unit. The -macModFiles tells the compiler to search the {f90includes} folder for compiled modules.

How Absoft Fortran 77 Interfaces with the Toolbox

A group of FORTRAN 77 include files with the file extension .inc allows Absoft Fortran 77 to interface with the Macintosh toolbox. These files contain FORTRAN 77 declarations for every routine and most of the structures, types, and constants defined in

Fortran User Guide 192 Macintosh Programming

Inside Macintosh, volumes I to VI. The files are named after the Macintosh managers to which they refer;; they are the same as the chapter titles in Inside Macintosh. To include one of these files, use a statement such as:

INCLUDE "Quickdraw.inc"

This INCLUDE statement will define all the Quickdraw information for a single program unit. To speed compilation and to define the same information for all program units within a file, place the INCLUDE statement in a GLOBAL DEFINE block at the top of the file:

GLOBAL DEFINE INCLUDE "Quickdraw.inc" END

There are many dependencies between the include files. As a convenience, all of the toolbox INCLUDE files contain conditional compilation directives which will automatically include the required files. So, although Quickdraw.inc requires Types.inc for certain structure definitions, it is not necessary to explicitly include it. For example:

INCLUDE "Dialogs.inc" is equivalent to:

INCLUDE "Types.inc" INCLUDE "Quickdraw.inc" INCLUDE "Windows.inc" INCLUDE "Events.inc" INCLUDE "Controls.inc" INCLUDE "TextEdit.inc" INCLUDE "Dialogs.inc"

Locating the Fortran 90/95 and FORTRAN 77 Interface Files

The Fortran 90/95 interface files are located in the {MPW}Interfaces:F90Includes folder. This folder contains both the .inc and the .mod files. The environment variable {F90Includes} is defined to reference this folder. You must use the -macModFiles option to search this folder during Fortran 90/95 USE statement processing. If the - macModFiles is not used, the compiler will be unable to find the pre-compiled Macintosh toolbox modules.

The FORTRAN 77 .inc interface files are located in the {MPW}Interfaces:Fincludes folder. The environment variable {FIncludes} is defined to reference this folder. Interface files are accessed using the INCLUDE statement which first searches for the file in the current folder, next, in any folders specified with the -I compiler option, and finally, in any folders specified with the {FIncludes} variable. See the chapter The FORTRAN 77 Program in the FORTRAN 77 Language Reference Manual for details on using the INCLUDE statement. See the chapter Using the Compiler in this manual for a discussion of the -I compiler option.

Fortran User Guide Macintosh Programming 193

If, for any reason, you want to move the INCLUDE files to another directory, you must inform the compiler of the new location by setting the environment variable {FIncludes} to the new folder.

This can be done by modifying the UserStartup•Fortran script so this environment variable is set every time MPW is launched.

Set FIncludes path Export FIncludes

Passing Arguments By language definition, Fortran passes all arguments and receives all dummy arguments by reference. Absoft FORTRAN 77 and Fortran 90/95 can also pass arguments by value using the VAL() function and can receive dummy arguments by value using the VALUE statement.

Standard FORTRAN 77 and Fortran 90/95 pass all arguments by reference. This means that the memory address containing the argument is sent to the called subprogram, thereby allowing the subprogram to return information to the calling program as well as to use the value passed. Other languages, such as C and Pascal, allow a choice of passing by reference or passing by value. Passing by value is one way communication. A copy is created of the argument and passed to the subprogram. This copy may be used and modified but the actual argument is not changed.

To assist you with calling the toolbox from Fortran 90/95, Absoft Pro Fortran provides function interface blocks for each toolbox routine. The INTERFACE for MoveTo, found in Quickdraw.inc, is defined as follows:

INTERFACE SUBROUTINE MoveTo( & & h, & & v) INTEGER*2, VALUE :: h INTEGER*2, VALUE :: v END SUBROUTINE MoveTo END INTERFACE !DIR$ NAME(MOVETO="MoveTo")

Interfaces provide compile time argument type checking. If you call MoveTo with the wrong number of arguments or the type of either of the arguments is not INTEGER*2 the compiler will issue an error. The interface also specifies that both arguments are passed by value. The compiler will automatically pass by value all arguments declared in an interface as VALUE. This overrides the default Fortran 90/95 pass by reference mechanism. The !DIR$ NAME directive allows Fortran 90/95 to call mixed case routines such as MoveTo. By default the Fortran 90/95 compiler folds all names to uppercase.

Fortran User Guide 194 Macintosh Programming

You must be careful to pass the proper kind and type of argument to the toolbox routines. Failure to do so can cause incorrect results or even system crashes. Passing by reference is simple because it is the standard Fortran convention. Passing by value requires the use of INTERFACE blocks in Fortran 90/95, or the appropriately sized VAL() function in FORTRAN 77. To determine the correct argument order and type, refer to Inside Macintosh and to the .inc files containing the routines you want to call. The following Fortran 90/95 statement calls the toolbox routine MoveTo with two literal arguments:

CALL MoveTo(0_2, 0_2) ! x = 0 y = 0

The FORTRAN 77 equivalent is:

CALL MoveTo(VAL2(0), VAL2(0)) ! x = 0 y = 0

The Pascal declaration (from Inside Macintosh) for MoveTo is:

PROCEDURE MoveTo (h,v: INTEGER);

All variables passed must have the same size as the corresponding toolbox parameters. In particular, note that Pascal INTEGER variables, as used in Inside Macintosh, are 2 bytes, so Fortran INTEGER*2 variables which are the same size should be used. See the section Fortran Data Types in Pascal later in this chapter for a table of Fortran and Pascal data type compatibility. Passing more complex parameter types is discussed later in this chapter.

All pointers are 32 bits and must be declared as INTEGER*4 values or as POINTERs and passed as arguments with the VAL4 function. These calls pass a pointer to the SetPort routine in the toolbox:

INTEGER*4 p_front CALL SetPort(p_front)

TYPE(WindowRecord) :: front ! Fortran 90/95 POINTER(p_front, front) CALL SetPort(p_front)

RECORD /WindowRecord/ front ! FORTRAN 77 POINTER(p_front, front) CALL SetPort(VAL4(p_front))

RECORD /WindowRecord/ front ! FORTRAN 77 POINTER(p_front, front) CALL SetPort(front)

Newer versions of the Apple Inside Macintosh documentation use the C programming language to describe the interface to the toolbox routines. Absoft Pro Fortran is designed to interface directly to the C programming language enabling Fortran programs to call toolbox routines with the only requirement being careful attention to argument data types.

Fortran User Guide Macintosh Programming 195

IMPLICIT NONE Statement

Use of the IMPLICIT NONE statement is strongly recommended when calling the toolbox. The IMPLICIT NONE statement informs the compiler to issue errors for all undeclared variables, thereby forcing explicit declaration of all variables used. Placing this statement at the beginning of each program unit is the easiest way to avoid difficulties due to undeclared or misspelled variable names. The following code fragments are examples of using the IMPLICIT NONE statement:

SUBROUTINE asub ! Fortran 90/95 USE QUICKDRAW IMPLICIT NONE INTEGER x,y

x = 175 y = 35 CALL MoveTo(x, y) RETURN END

GLOBAL DEFINE ! FORTRAN 77 INCLUDE "Quickdraw.inc" END

SUBROUTINE asub IMPLICIT NONE INTEGER*4 x,y

x = 175 y = 35 CALL MoveTo(VAL2(x), VAL2(y)) RETURN END

Details about the Absoft Fortran 77 implementation of IMPLICIT statement can be found in the Specification and DATA Statements chapter of the FORTRAN 77 Language Reference Manual.

Initialization Routines Called by Pro Fortran Startup

If a program is running as an MPW tool, the Pro Fortran startup routine, InitFTool.o, calls InitGraf to initialize Quickdraw. MPW takes care of the other initializations listed below.

If a program is an application (the default), with or without MRWE, InitFApp.o calls no initialization routines since the Carbon Library performs all initialization.

Fortran User Guide 196 Macintosh Programming

Using MRWE and the Toolbox MRWE provides a Macintosh-style interface for generic Fortran programs and is not intended to be used in conjunction with programs that make extensive use of the Macintosh toolbox. Programs that have their own event loop or control their own windows will generally not use MRWE.

The MRWE example programs, however, demonstrate how MRWE may be used along with a custom window. In fact, some internal MRWE routines are called for the printing and saving of text.

Examples of complete programs that use the Macintosh toolbox and do not use MRWE are Snowflake.f90 and Snowflake.f which have their own event loops and control their own windows and menus.

Although the MRWE window grafport may be used for toolbox output, a text edit field covers the entire window contents and is updated, thus erasing the grafport, during most standard output or standard input.

Using STRUCTUREs and RECORDs with Toolbox

Here is an example of the PenState Pascal record, defined as:

TYPE PenState = RECORD pnLoc: Point; { pen location } pnSize: Point; { pen size } pnMode: Integer; { pen’s transfer mode } pnPat: Pattern { pen pattern } END;

The equivalent Fortran 90/95 structure is in the INCLUDE file Quickdraw.inc:

TYPE PenState SEQUENCE TYPE(Point) :: pnLoc TYPE(Point) :: pnSize INTEGER*2 pnMode INTEGER*1 pnPat(0:7) ENDTYPE PenState

The equivalent FORTRAN 77 structure is in the INCLUDE file Quickdraw.inc:

STRUCTURE /PenState/ RECORD /Point/ pnLoc RECORD /Point/ pnSize INTEGER*2 pnMode INTEGER*1 pnPat(0:7) END STRUCTURE

The toolbox for PowerPC based Macintosh computers is designed to be compatible with the toolbox for older 68000 based computers. PowerPC programs normally require data elements to be aligned on natural boundaries, which occasionally requires padding

Fortran User Guide Macintosh Programming 197 between structure elements to ensure proper alignment. The Absoft Pro Fortran compilers perform this padding by default so that programs will execute with optimum performance. However, structures used by toolbox routines are exceptions to this rule since 68000 programs running under emulation may also use them. Therefore, all structures passed to and returned from toolbox routines must be packed. All of the INCLUDE files provided with the compiler contain compiler directives to ensure that structures and records used with the toolbox are packed.

This sample Fortran 90/95 program uses the PenState derived type:

PROGRAM findpen

USE QUICKDRAW

TYEP(PenState) :: state

CALL GetPenState(state) WRITE(*,*) 'Horizontal coordinate of pen = ', state%pnLoc%h WRITE(*,*) 'Vertical coordinate of pen = ', state%pnLoc%v END

The CALL to the routine GetPenState passes, by value, the pointer to the state record. This means that the address of the record is passed.

The FORTRAN 77 equivalent using the PenState structure is:

GLOBAL DEFINE INCLUDE "Quickdraw.inc" END

PROGRAM findpen

RECORD /PenState/ state

CALL GetPenState(state) WRITE(*,*) 'Horizontal coordinate of pen = ', state.pnLoc.h WRITE(*,*) 'Vertical coordinate of pen = ', state.pnLoc.v END

Passing the Toolbox a Pointer to a Fortran Routine Certain toolbox routines require pointers to other routines as parameters. These may be routines that you write to customize a standard toolbox feature or they may be handlers for events that you wish to process asynchronously. The routine may be a PowerPC routine or a 68000 routine. To accommodate this complexity, the toolbox uses a mechanism called a Universal Procedure Pointer that communicates to the Mixed Mode Manager the type of routine that you are using.

NOTE: A Universal Procedure Pointer is not required to call a toolbox routine. It is only used when the toolbox routine will be making calls back to your routines.

Fortran User Guide 198 Macintosh Programming

A Universal Procedure Pointer is a data structure that specifies the address of the routine, the type of code it contains (PowerPC or 68000), the size the result argument (if any), the number of arguments in the parameter list, and the sizes of those arguments. Universal Procedure Pointers and the Mixed Mode Manager are completely described in the document: Inside Macintosh: PowerPC System Software, but it is not necessary to completely understand the mechanism to use it. The following discussion and examples should provide all of the information necessary to use these facilities for normal purposes.

The Absoft Pro Fortran compilation system provides a function called BuildDescriptor which creates a Universal Procedure Pointer descriptor and returns a pointer to it. The source code to this routine is also provided as BuildDescriptor.f. The constants and declarations for using BuildDescriptor are provided in the MixedMode.inc INCLUDE files. The Fortran 90/95 module information for BuildDescriptor is provided in the module ABSOFT_MIXEDMODE.

UPP = BuildDescriptor(routine,convention,result,count,arguments)

where: UPP is a pointer to a Universal Procedure Pointer descriptor and should be declared as an INTEGER variable.

routine is the address of the routine and must be declared in an EXTERNAL statement before appearing in the argument list to the BuildDescriptor function.

convention is an INTEGER argument describing the calling convention type and is usually stated as kPascalStackBased which describes PowerPC routines as well as the 68000 toolbox calling conventions.

result is an INTEGER argument which indicates the size of the result argument and must be one of the following: 0, 1, 2, or 4.

count is an INTEGER argument which indicates the number of arguments to the routine.

args is an INTEGER array of at least count elements. The array contains the sizes of each argument to the routine and must be one of the following: 0, 1, 2, or 4. Arguments passed by reference (pointers) will be 4-bytes long.

A typical use of a Universal Procedure Pointer is to pass the address of a custom filter routine to the ModalDialog toolbox routine. In Fortran 90/95:

USE MIXEDMODE USE ABSOFT_MIXEDMODE

Integer (kind=4) :: args(2) Integer (kind=2) :: hit

Fortran User Guide Macintosh Programming 199

Integer (kind=4) :: filter_UPP External filter

arg(1) = 4 ! size of pointer to dialog record arg(2) = 2 ! size of dialog item filter_UPP = BuildDescriptor(filter,kPascalStackBased,0,2,args) . call ModalDialog(filter_UPP,hit) . call DisposeRoutineDescriptor(filter_UPP)

In FORTRAN 77:

include "MixedMode.inc"

integer*4 args(2) integer*2 hit integer*4 filter_UPP external filter

arg(1) = 4 ! size of pointer to dialog record arg(2) = 2 ! size of dialog item filter_UPP = BuildDescriptor(filter,kPascalStackBased,0,2,args) . call ModalDialog(val(filter_UPP),hit) . call DisposeRoutineDescriptor(val(filter_UPP))

NOTE: The above examples do not contain all of the toolbox calls necessary to create, respond to, or dispose of the dialog. They are intended only to show the necessary calls to manage the Universal Procedure Pointer associated with a custom filter routine.

DisposeRoutineDescriptor must eventually be called to dispose of the memory that was allocated by BuildDescriptor, but only after the descriptor has been used. It may be more efficient to allocate Universal Procedure Pointer descriptors once at the beginning of a program for those routines that will be commonly used and then place the addresses of the descriptors in a COMMON block. Universal Procedure Pointers are used whenever you are passing a pointer to a function that will be called by the toolbox.

Handles The Macintosh Memory Manager can move certain blocks of memory at any time to a new location and pointers referencing data in those blocks will be left “dangling”, or pointing to an incorrect address. To avoid this, a data type called a handle is used. Handles use one level of indirection to access data they reference. The indirection is via a master pointer that exists for each moveable block. When the block is moved, the Memory Manager properly updates its master pointer and all handles are still valid because the master pointer has not moved. In other words, handles are pointers to pointers.

Fortran User Guide 200 Macintosh Programming

Handle • 

 

• 



Master Pointer  Master Pointer 

Handle Memory

Master Pointer 



Master Pointer 

  •  • •

A handle points to a pointer to a memory block Figure 9-2

Handles are dealt with in much the same manner as pointers. This section of code from the SetCurs.f example program, gets a handle to a cursor, dereferences it, and passes the dereferenced cursor record to SetCursor.

INTEGER*2 cType TYPE(Cursor) :: theCursor ! use a cursor structure POINTER(p_theCursor, theCursor) ! pointer to theCursor POINTER(h_theCursor, p_theCursor) ! pointer to a pointer (handle)

INTEGER*4 i, dummy

DO (cType = 1, 4) h_theCursor = GetCursor(cType) ! get a handle to cursor WRITE (*,10) cType, theCursor%hotSpot%h, theCursor%hotSpot%v WRITE (*,11) DO (i = 0, 15) WRITE (*, 20) i, theCursor.data(i), theCursor.mask(i) END DO WRITE (*,*) CALL SetCursor(theCursor) ! pass it to SetCursor CALL Delay(VAL4(120), dummy) ! delay for 2 seconds END DO

Fortran User Guide Macintosh Programming 201

Accessing the Quickdraw Globals A copy of the structure that contains the Quickdraw globals is placed in the predefined COMMON block absoft_QD during program startup. The structure is declared in the INCLUDE file quickdraw.inc as follows:

TYPE QDGlobals SEQUENCE INTEGER*1 privates(76) INTEGER randSeed TYPE(BitMap) :: screenBits TYPE(Cursor) :: arrow INTEGER*1 dkGray(0:7) INTEGER*1 ltGray(0:7) INTEGER*1 gray(0:7) INTEGER*1 black(0:7) INTEGER*1 white(0:7) TYPE(GrafPort) :: thePort ENDTYPE QDGlobals

The following example shows how to use it to determine how large the screen is that the programming is running on:

USE QUICKDRAW

INTEGER height, width

TYPE(QDGlobals) :: qd COMMON /absoft_QD/ qd

height = qd%screenBits%bounds%bottom width = qd%screenBits%bounds%right

NOTE: Access to the Quickdraw globals from within a Carbon application is performed with “accessor” functions. See the MRWE source code for examples.

Apple Events Apple events provide a mechanism whereby a program can receive and process messages from the Finder and from other applications. Apple provides over 100 pages of documentation on the Apple Event Manager in Inside Macintosh, Volume VI and it is beyond the scope of this manual to attempt to duplicate that effort here. However, this section will provide a basic understanding of Apple events and sufficient information to respond to the required set of events.

Apple events will only be sent to a program if the appropriate flags are set in the SIZE(- 1) resource (see The SIZE(-1) Resource later in this chapter). The two flags of interest are:

isHighLevelEventAware localAndRemoteHLEvents

Fortran User Guide 202 Macintosh Programming

There are four required events that every program must be able to respond to:

• Open Application • Open Document • Print Document • Quit Application

Like all other events, a program receives notification of an Apple event through the Event Manager by making a toolbox call such as WaitNextEvent. The program then makes a call to the toolbox routine AEProcessAppleEvent with the address of the event record. The Apple Event Manager then dispatches the event to the individual handler routines within the program. However, the program must first register the events that it will take responsibility for with the Apple Event Manager and supply the addresses of the routines that will handle the events. This is accomplished with the AEInstallhandler toolbox call that takes, as one of its arguments, a Universal Procedure Pointer that specifies the routine address. Universal Procedure Pointers were described earlier in this chapter in the section Passing the Toolbox a Pointer to a Fortran Routine:

Fortran User Guide Macintosh Programming 203

USE EVENTS USE APPLEEVENTS USE MIXEDMODE USE ABSOFT_MIXEDMODE USE EPPC

integer oapp; external oapp ! open application routine integer odoc; external odoc ! open document routine integer pdoc; external pdoc ! print document routine integer quit; external quit ! quit application routine

integer oapp_UPP ! oapp Universal Procedure Pointer integer odoc_UPP ! odoc Universal Procedure Pointer integer pdoc_UPP ! pdoc Universal Procedure Pointer integer quit_UPP ! quit Universal Procedure Pointer

integer args(3) integer*2 OSErr

args(1) = 4 ! AppleEvent record args(2) = 4 ! reply record args(3) = 4 ! RefCon

oapp_UPP = BuildDescriptor(oapp,kPascalStackBased,2,3,args) OSErr = AEInstallEventHandler(kCoreEventClass, & kAEOpenApplication, & oapp_UPP,0,.false._1)

odoc_UPP = BuildDescriptor(odoc,kPascalStackBased,2,3,args) OSErr = AEInstallEventHandler(kCoreEventClass, & kAEOpenDocuments, & odoc_UPP,0,.false._1)

pdoc_UPP = BuildDescriptor(pdoc,kPascalStackBased,2,3,args) OSErr = AEInstallEventHandler(kCoreEventClass, & kAEPrintDocuments, & pdoc_UPP),0,.false._1)

quit_UPP = BuildDescriptor(quit,kPascalStackBased,2,3,args) OSErr = AEInstallEventHandler(kCoreEventClass, & kAEQuitApplication, & quit_UPP),0,.false._1)

After this initialization process, the program is ready to respond to these events. The type of event that the Event Manager will report is a kHighLevelEvent, defined in the EPPC.inc INCLUDE file. If the program is using a SELECT CASE block in its event loop, the Apple event dispatch code will look like this:

do call WaitNextEvent(int(everyEvent,2),event,1,0) select case (event.what) . case (kHighLevelEvent) OSErr = AEProcessAppleEvent(event) . end select end do

Fortran User Guide 204 Macintosh Programming

The AEProcessAppleEvent toolbox call will invoke the appropriate handler routine to process the event. The handler routine can return an error code to the event loop, allowing the program to gracefully unwind itself in the event an error occurs. Each of these routines will have the same basic format. In Fortran 90/95:

integer*2 function oapp(event,reply,RefCon)

type(AEDesc) :: event type(AEDesc) :: reply integer RefCon value RefCon . oapp = 0 ! non-zero return value indicates an error

end

In FORTRAN 77:

integer*2 function oapp(event,reply,RefCon)

record /AEDesc/ event record /AEDesc/ reply integer RefCon value RefCon . oapp = 0 ! non-zero return value indicates an error

end

This will usually be all that an Open Application handler will have to do. A Quit Application handler will call the normal quit or exit routines of the program and obviously never return. An Open Document handler will first call the toolbox routine AEGetParamDesc to fill out an Apple event descriptor with the list of documents to open. AECountItems returns the count of the number of items in the document list. The routine will then cycle through the list, calling AEGetNthPtr to obtain a pointer to the file specification of each document. The file specifications are passed to the program’s actual open document routine (called OpenDocument in the example below). After all of the documents have been processed, AEDisposeDesc disposes of the Apple event descriptor. The following function represents a minimum Open Document handler routine:

Fortran User Guide Macintosh Programming 205

integer*2 function odoc(event,reply,RefCon)

use FILES use APPLEEVENTS

implicit none

type(AEDesc) :: event type(AEDesc) :: reply integer RefCon value RefCon

integer*2 OSErr type(AEDesc) :: docList

integer keywd, returnedType type(FSSpec) :: file integer size

integer i, n

odoc = 1

OSErr = AEGetParamDesc(event,keyDirectObject, typeAEList,docList) if (OSErr <> 0) return

OSErr = AECountItems(docList,n)

do i=1, n OSErr = AEGetNthPtr(docList,i,typeFSS, & keywd,returnedType, & loc(file),sizeof(/FSSpec/),size) if (OSErr == 0) call OpenDocument(file) end do

OSErr = AEDisposeDesc(docList)

odoc = 0

end

A function for handling print document events will look similar, replacing the OpenDocument reference with a call to a PrintDocument routine.

Fortran User Guide 206 Macintosh Programming

MACINTOSH TOOLBOX EXAMPLES

This section highlights the features of the example programs in the FExamples folder. These examples are designed to answer the most common questions received by Absoft Technical Support. They include demonstrations of graphics, printing, access to the Macintosh serial ports, and standard user interface techniques.

Many of the example programs contain calls to the Macintosh toolbox. Some of the examples use the Macintosh Runtime Window Environment (MRWE) for standard input and output along with toolbox calls to create graphics. There may be additional example programs in the FExamples folder that are not listed here. Read the comments in the example programs themselves for more information.

Example program Description ARGSt A subroutine to retrieve the command line arguments in a tool. DateTime Demonstrates how to get the system date and time. GetSet A program that demonstrates calling the function in StdFil.f90/StdFil.f. GetFinderInfo Extracts Finder information from an application. Random Demonstrates how to get random numbers. SetCurs Displays four default mouse pointer cursors and demonstrates the proper way to lock and dereference a handle. Snowflake A complete Macintosh application that demonstrates using Quickdraw for drawing “snowflakes”. StdFil A function for displaying the standard file dialogs for selecting and naming files. Term A simple terminal program that uses the serial port. Whet The popular Whetstone benchmark.

INTERFACING WITH OTHER LANGUAGES This section describes how Absoft Pro Fortran interfaces with C, Pascal, and assembly language. Although Fortran programs can call C and Pascal subroutines easily with just a CALL statement, the sections below should be read carefully to understand the differences between argument and data types. The interfaces to C detailed below apply specifically to Absoft C/C++ and should be similar for MPW compilers available from other vendors. For information about linking C and Pascal, consult the manuals accompanying those compilers.

Fortran User Guide Macintosh Programming 207

Interfacing with C Absoft Pro Fortran is designed to be fully compatible with the implementation of the standard C language on the Macintosh. The linker can be used to freely link C modules with Fortran main programs and vice versa. However, some precautions must be taken to ensure proper interfacing. Data types in arguments and results must be equivalent. The case of global symbols on the Macintosh is significant. The symbolic names of external procedure must match in case.

Fortran Data Types in C

Declarations for Fortran data types and the equivalent declarations in C are as follows:

Fortran C

LOGICAL*1 l unsigned char l; LOGICAL*2 m unsigned short m; LOGICAL*4 n unsigned long n;

CHARACTER*n c char c[n];

INTEGER*1 i or BYTE i char i; INTEGER*2 j short j; INTEGER*4 k int k; long k;

REAL*4 a float a; REAL*8 d double d;

COMPLEX*8 c struct complx { float x; float y; }; struct complx c;

COMPLEX*16 d struct dcomp { double x; double y; }; struct dcomp d;

The storage allocated by the C language declarations will be identical to the storage allocated by the corresponding Fortran declaration.

There are additional precautions when passing Fortran strings to C routines. See the section Passing Strings to C later in this chapter for more information.

Passing Values Between C and Fortran

The Absoft Pro Fortran compilers uses the same calling conventions as the C programming language. Therefore, a Fortran routine may be called from C without being declared in the C program and vice versa, if the routine returns all results in parameters.

Fortran User Guide 208 Macintosh Programming

Otherwise, the function must be typed compatibly in both program units. In addition, care must be taken to pass compatible parameter types between the languages. Refer to the table above.

Reference parameters

All Fortran arguments to routines are passed by reference, which means pointers to the data are passed, not the actual data. Therefore, when calling a Fortran procedure from C, pointers to arguments must be passed rather than values. Both integer and floating point values may be passed by reference. Consider the following example:

SUBROUTINE SUB(a_dummy,i_dummy) REAL*4 a_dummy INTEGER*4 i_dummy

WRITE (*,*) 'The arguments are ',a_dummy, ' and ', i_dummy RETURN END

The above subroutine is called from Fortran using the CALL statement:

a_actual = 3.3 i_actual = 9 CALL SUB(a_actual, i_actual) END

However, to call the subroutine from C, the function reference must explicitly pass pointers to the actual parameters as follows:

int main() { float a_actual; int i_actual; void SUB();

a_actual = 3.3; i_actual = 9; SUB(&a_actual,&i_actual); return 0; }

Note that the values of the actual parameters may then be changed in the Fortran subroutine with an assignment statement or an I/O statement.

When calling a C function from Fortran with a reference parameter, the C parameters are declared as pointers to the data type and the Fortran parameters are passed normally:

PROGRAM convert_to_radians WRITE (*,*) 'Enter degrees:' READ (*,*) c CALL C_RAD(c) WRITE (*,*) 'Equal to ',c,' radians' END

Fortran User Guide Macintosh Programming 209

void C_RAD(c) float *c; { float deg_to_rad = 3.14159/180.0; *c = *c * deg_to_rad; }

Value parameters

Absoft Pro Fortran provides the intrinsic function %VAL() for passing value parameters. Function interfaces may also be used to specify which arguments to pass by value. Although it is generally pointless to pass a value directly to a Fortran procedure, these functions may be used to pass a value to a C function. The following is an example of passing a 4-byte integer:

WRITE (*,*) 'Enter an integer:' READ (*,*) i CALL C_FUN(VAL(i)) END

void C_FUN(i) int i; { printf ("%d is ",i); if (i % 2 == 0) printf ("even.\n"); else printf ("odd.\n"); }

The value of i will be passed directly to C_FUN, and will be left unaltered upon return. Value parameters can be passed from C to Fortran with use of the VALUE statement. The arguments that are passed by value are simply declared as VALUE.

void C_FUN() { void FORTRAN_SUB(); int i;

FORTRAN_SUB(i); }

SUBROUTINE FORTRAN_SUB(i) VALUE i ... END

Note that C will pass all floating-point data as double precision by default, and that the only Fortran data type that cannot be passed by value is CHARACTER.

Fortran User Guide 210 Macintosh Programming

Array Parameters

One-dimensional arrays can be passed freely back and forth as both language implementations pass arrays by reference. However, since C and Fortran use different row/column ordering, multi-dimensional arrays cannot be easily passed and indexed between the languages.

INTEGER ia(10)

CALL C_FUN(ia) WRITE (*,*) ia

END

void C_FUN(i) int i[]; { int j; for(i=0;j<10;j++) i[j]=j; }

Function Results

In order to obtain function results in Fortran from C language functions and vice versa, the functions must be typed equivalently in both languages: either INTEGER, REAL, or DOUBLE. All other data types must be returned in reference parameters. The following are examples of the passing of function results between Fortran and C. The names are case- sensitive, so trying to call CMAX, for example, will result in an error at link time.

A call to C from Fortran

PROGRAM callc INTEGER*4 CMAX, A, B

WRITE (*,*) 'Enter two numbers:' READ (*,*) A, B WRITE (*,*) 'The largest of', A, ' and', B, ' is ', CMAX(A,B) END

int CMAX (x,y) int *x,*y; { return( (*x >= *y) ? *x : *y ); }

Fortran User Guide Macintosh Programming 211

A call to Fortran from C

main() { float QT_TO_LITERS(), qt;

printf ("Enter number of quarts:\n"); scanf ("%f",&qt); printf("%f quarts = %f liters.\n", qt, QT_TO_LITERS(&qt)); }

REAL*4 FUNCTION QT_TO_LITERS(q) REAL*4 q;

QT_TO_LITERS = q * 0.9461; END

Passing Strings to C

Fortran strings are a sequence of characters padded with blanks out to their full fixed length, while strings in C are a sequence of characters terminated by a null character. Therefore, when passing Fortran strings to C routines, you must terminate them with a null character. The following Fortran expression will properly pass the Fortran string string to the C routine CPRINT:

PROGRAM cstringcall character*255 string string = 'Moscow on the Hudson' CALL CPRINT(TRIM(string)//CHAR(0)) END

void CPRINT (anystring) char *anystring; { printf ("%s\n",anystring); }

This example will neatly output “Moscow on the Hudson”. If the TRIM function were not used, the same string would be printed, but followed by 235 blanks. If the CHAR(0) function was omitted, C would print characters until a null character was encountered, whenever that might be.

Calling Fortran math routines

All of the Fortran intrinsic math functions which return values recognized by the C language can be called directly from C as long as the Fortran run time library, libfmath.o, is linked to the application.

Taking the intrinsic function names in lower case and adding two underscores to the beginning forms the names of the functions that can be called.

Fortran User Guide 212 Macintosh Programming

The following example calls the Fortran intrinsic function SIN directly from C:

main() { float sin_of_a, a, __sin();

a = 3.1415926/6; sin_of_a = __sin(a); }

Accessing COMMON blocks from C

COMMON block names are global symbols formed in Absoft Fortran 90/95 by prepending the characters “_C” to the name of the COMMON block. The elements of the COMMON block can be accessed from C by declaring an external structure using this name. For example,

COMMON /comm/ a,b,c

can be accessed with the C declaration:

extern struct { float a; float b; float c; } _CCOMM;

Interfacing with Pascal Absoft compilers are generally compatible with the various implementations of Pascal. Routines in one language may be called from the other as long as they have been explicitly identified. The section Setting Up Inter-Language Calls later in this chapter explains how to do this.

Fortran User Guide Macintosh Programming 213

Fortran Data Types in Pascal

Declarations for Fortran data types and the equivalent declarations in Pascal are as follows:

Fortran Pascal

LOGICAL*1 l l: boolean; LOGICAL*2 m m: boolean;

CHARACTER*n c c: packed array[1..n] of char; c: string[n];

INTEGER*2 j j: integer; INTEGER*4 k k: longint;

REAL*4 a a: real; a: single; REAL*8 d d: double;

COMPLEX*8 c Type Comp_type = Record x: real; { real part } y: real; { imaginary part } End; Var c: Comp_type

COMPLEX*16 d Type Compd_type = Record x: double; y: double; End; Var d: Compd_type

The storage allocated by the Pascal language declarations will be identical to the storage allocated by the corresponding Fortran declaration. Be sure to use equivalent types when passing parameters between languages or your results will be invalid.

There are additional cautions when passing Fortran strings to Pascal routines. See the section Passing Strings to Pascal later in this chapter for more information.

Setting up Inter-Language Calls

Fortran and Pascal calling conventions differ. One key difference is that Fortran evaluates function parameters from right-to-left while Pascal evaluates left-to-right. This would cause the values on the stack upon entry to be misinterpreted. In addition, Pascal expects function results to be returned on the stack while Fortran returns them in registers. Obviously, in order for a Fortran program to communicate with a Pascal program or vice versa, the programs must know that they are interfacing with the other languages so adjustments may be made. The correct declarations are given below.

Fortran User Guide 214 Macintosh Programming

Declaring Pascal routines to be called from Fortran

From Fortran, the statements PASCAL and EXTERNAL are used to identify Pascal routines. PASCAL causes Fortran to expect results on the stack and to evaluate the parameters left to right, while EXTERNAL tells the compiler that the routine is declared in a different program unit. The Fortran declarations have the following format for Pascal functions and procedures, respectively:

type p_func PASCAL EXTERNAL p_func

PASCAL EXTERNAL p_proc

The routines in Pascal must be declared in a special format known as a unit. A Pascal unit is similar to a program, except that it is not executable by itself. This form is necessary because if the Pascal source file has a PROGRAM statement, it will become the main program, and the calls from Fortran will be ignored. Units are declared in Pascal using the following form:

UNIT unitname;

INTERFACE Function p_func (parameters) : type; Procedure p_proc (parameters);

IMPLEMENTATION Function p_func; Begin . . . End;

Procedure p_proc; Begin . . . End; END.

Anything (constants, types, variables, routines) declared in the INTERFACE section is available to all outside programs which link to the unit, and anything declared in the IMPLEMENTATION section is accessible only within the unit. You can see this from how the routine headers are defined in the INTERFACE section, and routine bodies in the IMPLEMENTATION section. The parameter lists and function result types are not repeated in the IMPLEMENTATION section.

Once these declarations are complete, the Pascal routines can be called in the same manner as Fortran routines, with functions returning values to the calling point within expressions, and procedures being accessed via the CALL statement. It can be seen from this that Pascal functions are analogous to Fortran functions and Pascal procedures to

Fortran User Guide Macintosh Programming 215

Fortran subroutines. For the routines declared above, these calls from Fortran would suffice:

type p_func PASCAL EXTERNAL p_func

PASCAL EXTERNAL p_proc

type a a = p_func (arguments) CALL p_proc(arguments)

Declaring Fortran routines to be called from Pascal

Two methods exist to allow a Fortran routine to be called from Pascal. The first way is to declare the routine as Pascal inside the Fortran program. This is done by placing the statement PASCAL in front of the Fortran routine declaration:

PASCAL type FUNCTION f_func (arguments) PASCAL SUBROUTINE f_sub (arguments)

Once this is done, the routines may be referenced directly from Pascal as would any external functions written in Pascal. The Pascal directive EXTERNAL is used to declare the routines in the following way:

Function f_func (VAR parameters) : type; EXTERNAL; Procedure f_sub (VAR parameters); EXTERNAL;

The second method is to have the Pascal program declare each Fortran routine as an external C routine with the C and EXTERNAL directives. The C directive causes Pascal to use the C/Fortran calling conventions, evaluating parameters from right to left, and returning function results in the registers expected by Absoft Fortran 90/95. The EXTERNAL directive makes the program look externally for the routine declaration. The directives are appended to the routine header as shown here:

Function f_func (VAR parameters) : type; C; EXTERNAL; Procedure f_sub (VAR parameters); C; EXTERNAL;

These Pascal declarations would be appropriate for the Fortran routine declarations above if the PASCAL directive was removed from the Fortran code. Either of these two methods allows the Fortran routines to be called in a normal fashion from Pascal. Note that all the Pascal parameters are declared with the keyword VAR. The reason for this will be explained in the next section.

Passing Values Between Pascal and Fortran

In Fortran, all arguments to subroutines and functions are passed by reference. This means that a pointer to the data item is passed rather than the actual data. Since Pascal provides a choice between reference and value passing, passing data between the two

Fortran User Guide 216 Macintosh Programming languages requires careful determination of the proper parameter types. See the section Fortran Data Types in Pascal earlier in this chapter for more details.

Reference parameters

Before calling a Fortran subroutine or function from Pascal, all arguments must be declared as by reference. This is done using the VAR keyword. Note that both floating point and integer values may be passed. For instance, here are two versions of a subroutine to be called from Pascal:

SUBROUTINE stats1(X,Y,S,A) PASCAL SUBROUTINE stats2(X,Y,S,A) REAL*4 X,Y,S,A REAL*4 X,Y,S,A

S = X+Y S = X+Y A = S/2 A = S/2 RETURN RETURN END END

Subroutine stats1 may be called from Fortran in the following manner:

CALL stats1(6.5, 3.0, sum, average)

Subroutine stats2, however, cannot be called directly from Fortran because it now behaves exactly like a Pascal routine. However, both versions may be called from Pascal simply be varying their declarations as follows (taking care to use VAR for all parameter definitions):

Program calcstats; Var x, y, avg, sum : Real;

Procedure stats1(VAR a, b, sum, avg : Real); C; EXTERNAL; Procedure stats2(VAR a, b, sum, avg : Real); EXTERNAL;

Begin x := 4.7; y := 3.0; stats1(x, y, sum, avg); Writeln('Sum and average = ', sum, ',', avg); x := 6.5; y := 3; stats2(x, y, sum, avg); Writeln('Sum and average = ', sum, ',', avg); End.

Notice that the values of the actual parameters can be changed in the Fortran subroutine since they are called by reference.

Fortran User Guide Macintosh Programming 217

Value parameters

Absoft Pro Fortran provides the intrinsic function %VAL for passing value parameters to Pascal. The following is an example of passing a 4-byte integer:

PASCAL EXTERNAL p_proc

i = 10 CALL p_proc(%VAL(i)) END

UNIT pfcall;

INTERFACE Procedure p_proc(n : longint);

IMPLEMENTATION Procedure p_proc; Begin While (n > 0) do Begin Writeln(n); n := n - 1; End; End; END.

The value of i will be passed directly to p_proc, and will be left unaltered upon return.

Value parameters can be passed from Pascal to Fortran with use of the VALUE statement. The arguments that are passed by value are simply declared as VALUE.

UNIT fpcall;

INTERFACE Procedure fortran_sub(n : longint); C; EXTERNAL;

IMPLEMENTATION Procedure p_proc; Begin fortran_sub(5); End; END.

SUBROUTINE fortran_sub(i) VALUE i ... END

Note that Pascal will pass all real and double by reference. The CHARACTER data type cannot be passed by value.

Fortran User Guide 218 Macintosh Programming

Function Results

To successfully return function results to Fortran from Pascal functions and vice versa, the functions must be declared with compatible types in both languages (see the table of Fortran and Pascal types at the beginning of the section Interfacing with Pascal). Also, as described in the section Setting up Inter-Language Calls, Pascal functions must be defined specially before being called. The following are examples of passing function results between Fortran and Pascal.

A call to Pascal from Fortran

REAL*4 in_to_cm PASCAL EXTERNAL in_to_cm

WRITE(*,*) 'Enter number of inches:' READ(*,*) B WRITE(*,*) B, ' inches = ', in_to_cm(B), ' centimeters.' END

UNIT pfcall; INTERFACE Function in_to_cm(VAR inches : Real) : Real;

IMPLEMENTATION Function in_to_cm; Begin in_to_cm := inches * 2.54; End; End.

A call to Fortran from Pascal

Program example; Function fsin1 (VAR a : Real) : Real; C; EXTERNAL; Function fsin2 (VAR a : Real) : Real; EXTERNAL; Var x : Real;

Begin x := 3.14159 / 3.0; (* 60 degrees in radians *) Writeln('Sine of ', x, ' = ', fsin1(x)); Writeln('Sine of ', x, ' = ', fsin2(x)); End.

Fortran User Guide Macintosh Programming 219

REAL*4 FUNCTION fsin1(A) REAL*4 A fsin1 = SIN(A) RETURN END

PASCAL REAL*4 FUNCTION fsin2(A) REAL*4 A fsin2 = SIN(A) RETURN END

Passing Strings to Pascal

A Fortran string is a sequence of characters padded with blanks to its full declared length. A Pascal string is a sequence of characters with its length contained in its first byte. Therefore, when passing Fortran strings to Pascal routines, you must attach a byte containing the length of the string to the beginning of it. This example demonstrates the proper format:

PROGRAM pstringcall CHARACTER*50 str50 PASCAL EXTERNAL PPrint str50 = CHAR(12)//'twelve chars' CALL PPrint(str50) END

UNIT pfcall; INTERFACE Type Str20 = string[20]; Procedure PPrint (VAR astr : Str20);

IMPLEMENTATION Procedure PPrint; Begin Writeln(astr, ' is ', Length(astr), ' characters long.'); End; End.

This example will print “twelve chars is 12 characters long.” Without the length byte, Pascal will use the first character as the length and produce erroneous and unpredictable results.

Calling Fortran math routines

All of the Fortran intrinsic math functions which return values recognized by the Pascal language can be called directly from Pascal as long as:

• the Fortran math library libfmath.o is linked to the application.

• the function is declared with the C and EXTERNAL directives.

Fortran User Guide 220 Macintosh Programming

The names of the functions which can be called are formed by taking the intrinsic function names in lower case and adding two underscores to the beginning.

The following example calls the Fortran intrinsic function SIN directly from Pascal:

Program call_fortran_sine;

Function __sin (Real) : Real; C; EXTERNAL;

VAR a, sina : Real;

Begin a := 3.14159 / 6; sina := __sin(a); End.

Interfacing with Assembly Language This section discusses how arguments and results are passed on the stack and in registers.

The Fortran Stack Frame The addresses of arguments to a Fortran procedure are passed in a right to left order in registers r3-r10 or in the stack. The lengths of character arguments are passed as 32 bit integers above the addresses. On entry to a Fortran procedure, the stack frame is defined as follows:

Subroutine declaration: SUBROUTINE sub(arg 1, ... ,arg n)

(n*4)+((q-1)*4)+(sp+24) length of character arg q . . . (n*4)+(sp+24) length of character arg 1 ((n-1)*4)+(sp+24) address of arg n . . . (sp+24) address of arg 1

argument position = ((m-1) * 4)) + 24 length position = (n * 4 + (q-1) * 4) + 24

where: m = argument number n = total arguments q = character argument number

The Fortran Stack Frame Figure 9-3

Fortran User Guide Macintosh Programming 221

Upon entry to a procedure, the addresses of the first eight arguments will be passed in registers r3-r10 and the address of any additional argument will be passed in the stack frame. Space for locally saving the arguments passed in registers will have been allocated in the stack frame. The length field is allocated only for CHARACTER argument types and immediately follows the actual arguments in the stack.

Value arguments for all non-floating-point arguments except CHARACTER are passed in registers (if there is enough space in registers r3-r10) or in the stack. Floating-point value arguments are passed in registers f1-f13. Space in registers r3-r10 is skipped to correspond to arguments passed in floating-point registers. For example, if a procedure reference has three arguments passed by value and they are an integer, a double precision value and another integer in that order, the first argument will be passed in r3, the second in f1 and the third in r6.

Space for CHARACTER and derived type function results is passed as if it were an extra argument at the beginning of the argument list. For example, the following two calls are equivalent in respect to how arguments are passed to the external function or subroutine:

CHARACTER*10 funct, arg, result EXTERNAL sub

result = funct(argument) CALL sub(result,argument)

Function Results Absoft Fortran 90/95 returns all numeric and logical function results except derived type in the caller’s register r3 or in the registers f1 and f2 depending on the width and data type of the result.

CHARACTER and derived type results are not returned in registers. The address of space for the result is passed in as the first argument.

RESOURCES It is beyond the scope of this manual to fully discuss resources. This section is designed from the “how to” viewpoint with Fortran in mind. For complete information about using resources, see the “Resource Manager” chapter of Inside Macintosh.

A resource editor, such as ResEdit, available from APDA, is very useful for modifying existing resources or copying resources between files. The MPW tool Rez, included with Absoft Fortran 90/95, is a resource compiler that creates new resources based on a textual resource description file. Rez is documented in Chapter 8 along with DeRez, a decompiler of resources that generates a resource description file.

By looking at existing resource description files in the FExamples folder and using DeRez to create new ones, much can be learned about the language syntax of resource

Fortran User Guide 222 Macintosh Programming

description files. The paragraphs below will show, by example, the most common constructs. For a complete description of the language, see the Macintosh Programmer’s Workshop Manual. Examples are given below for adding ICON and SIZE resources to applications. These are used by the Finder to determine the icon to use for an application and the amount of memory to set aside for an application.

Include Files

Every resource description file must include the file Types.r which defines standard Macintosh resources. It is located in the RIncludes folder. The following line placed in column one at the top of a resource description file will do this:

#include "Types.r"

More specialized resources are in the RIncludes folder.

Adding an Icon to an Application A few resources must be added to an application for the Finder to correctly display a unique icon for an application instead of the default application icon. The following example defines the ICN#, BNDL, and FREF resources. The resource FSMP can have any name but must match the creator that is set with the -c type linker option. See the chapter “Finder Interface” in Inside Macintosh for details about how these resources are used by the Finder. This code is from the Snowflake.r file in the FExamples folder.

data 'FSMP' (0) { $"24 53 61 6D 70 6C 65 20 46 37 37 20 41 70 70 6C" $"69 63 61 74 69 6F 6E 20 2D 20 56 65 72 73 69 6F" $"6E 20 31 2E 30" };

resource 'ICN#' (128) { { /* array: 2 elements */ /* [1] */ $"00 00 00 00 70 EF CE 0E 49 28 2A EA 46 2B AA AA" $"50 AA AA AA 59 AB AA AA 56 A8 2A AA 50 AB CA AA" $"50 AA 0B 1A 50 AA 08 42 70 EE 0F BE 00 00 00 00" $"00 00 00 00 7F FF FF FE 40 00 00 02 47 EF F7 FA" $"47 EF F7 FA 46 00 30 1A 46 00 60 32 47 80 C0 62" $"47 81 80 C2 46 03 01 82 46 06 03 02 46 0C 06 02" $"46 0C 06 02 46 0C 06 02 40 00 00 02 7F FF FF FE", /* [2] */ $"00 00 00 00 70 EF CE 0E 79 EF EE EE 7F EF EE EE" $"7F EE EE EE 7F EF EE EE 76 EF EE EE 70 EF CE EE" $"70 EE 0F FE 70 EE 0F FE 70 EE 0F BE 00 00 00 00" $"00 00 00 00 7F FF FF FE 7F FF FF FE 7F FF FF FE" $"7F FF FF FE 7F FF FF FE 7F FF FF FE 7F FF FF FE" $"7F FF FF FE 7F FF FF FE 7F FF FF FE 7F FF FF FE" $"7F FF FF FE 7F FF FF FE 7F FF FF FE 7F FF FF FE" } };

Fortran User Guide Macintosh Programming 223

resource 'BNDL' (128) { 'FSMP',

{ /* array TypeArray: 2 elements */ /* [1] */ 'ICN#', { /* array IDArray: 1 elements */ /* [1] */ 128 }, /* [2] */ 'FREF', { /* array IDArray: 1 elements */ /* [1] */ 128 } } };

resource 'FREF' (128) { 'APPL',

"" };

An icon, other than the default application icon, can be added to applications that use MRWE by adding these resources to the MRWE.r file and rebuilding the MRWE library as described in the Read Me file of the MRWE folder.

All applications that use MRWE have the following balloon help for its icon when shown in the Finder.

The help is simply defined in a ‘hfdr’ resource with ID -5696. This code is from the MRWE.r file in the FExamples:MRWE folder:

Fortran User Guide 224 Macintosh Programming

resource 'hfdr' (-5696) { HelpMgrVersion, hmDefaultOptions, 0, 0, { HMStringItem { "This application was developed using the Absoft " "Fortran 90 globally optimizing compiler." } } };

The SIZE(-1) Resource When an application is launched, the SIZE resource with an ID of -1, if any, is examined to determine how much memory the application requires. The SIZE(-1) resource from the file Snowflake.r is shown below and sets the minimum memory size to 48K and the preferred to 64K. These are the values that appear in the Get Info… dialog box from the Finder. The other elements of the SIZE(-1) resource are listed in the types.r Resource Manager interface file and documented in the Event Manager chapter of Inside Macintosh, Volume VI listed in Appendix D.

resource 'SIZE' (-1) { dontSaveScreen, acceptSuspendResumeEvents, enableOptionSwitch, canBackground, /* We can background */ multiFinderAware, /* We do our own activate/deactivate */ backgroundAndForeground, /* Not a background-only application */ dontGetFrontClicks, /* Don’t get click event on activate */ ignoreChildDiedEvents, not32BitCompatible, /* Not for 32-bit address space */ reserved, reserved, reserved, reserved, reserved, reserved, reserved, * 64, /* Preferred size, 64K */ * 48 /* Minimum size, 48K */ };

The SIZE(-1) resource may be modified for applications that use MRWE by editing the MRWE.r file and rebuilding the MRWE library as described in the Read Me file of the MRWE folder. By default, MRWE has a SIZE(-1) resource that specifies 384K for the minimum and preferred sizes for applications. This value may be increased for large applications that need more memory when using MultiFinder.

The minimum size can also be set from the Get Info… dialog. Any changes made in this way will be lost, however, the next time the application is generated.

Fortran User Guide Macintosh Programming 225

Compiling a Resource Description File

The following invocation of Rez, from the Snowflake.make file, compiles the resource description file and appends it to the application Snowflake.

Rez -rd Snowflake.r -o Snowflake -append

DEBUGGING Debugging a Fortran program is accomplished with the Absoft source-level debugger, Fx™. This is a multi-language, windowed debugger designed especially for the PowerPC based Macintosh computers. The operation of the debugger is detailed in the next chapter, Using the Fx Debugger. The following paragraphs describe the compiler options and resources necessary to prepare a program for debugging.

NOTE: Only desktop applications, with or without MRWE, can be debugged with Fx. It is not possible to use the debugger on MPW tools.

Compiler Options

The -g compiler option (Debug with Fx from the commando dialog) directs the compiler to add symbol and line number information to the object file. This option should be enabled for each source file that you will want to have source code displayed while debugging. It is not required for files that you are not interested in.

It is recommended that all optimization options be disabled while debugging. This is because the optimizers can greatly distort the appearance and order of execution of the individual statements in your program. Code can be removed or added (for loop unrolling), variables may be removed or allocated to registers (making it impossible to examine or modify them), and statements may be executed out of order.

Linker Options

The -sym on option must be added to the command line for the linker. If you are using the commando dialog for the compiler, this will be done automatically. If you have created a Build script, you should add the option to the command line for lnk.

The symbol file created by the linker will have the same name as the application with the characters .FxSym appended to the end.

Size Resource

An application must have a SIZE resource with the canBackground flag set in order to be debugged. See The SIZE(-1) Resource section earlier in this chapter.

Fortran User Guide 226 Macintosh Programming

PROFILING The Absoft source-level debugger, Fx, is also used to gather profile information about an application. Profmt, a tool supplied with the compiler is used to display the profile statistics in both tabular format and graphically. The operation of Fx and Profmt for profiling is described in the next chapter, Using the Fx Debugger. The following paragraphs describe the compiler options and resources necessary to prepare a program for profiling.

NOTE: Only desktop applications, with or without MRWE, can be debugged with Fx. It is not possible to use the debugger on MPW tools.

Compiler Options

The -p compiler option (Generate profiler information from the commando dialog) directs the compiler to add the symbol information to the object file necessary to profile an application. Enabling this option will allow the debugger to report the number of times a particular subroutine is called or a function is referenced.

All other options that you would normally use should be enabled, including optimization.

Linker Options

The -sym on option must be added to the command line for the linker. If you are using the commando dialog for the compiler, this will be done automatically. If you have created a Build script, you should add the option to the command line for lnk.

The symbol file created by the linker will have the same name as the application with the characters .FxSym appended to the end.

Size Resource

An application must have a SIZE resource with the canBackground flag set in order to be debugged. See The SIZE(-1) Resource section earlier in this chapter.

Fortran User Guide 227

CHAPTER 10

Using the Fx Debugger

INTRODUCTION TO FX Fx is a multi-language, source-level symbolic debugger for the Macintosh PowerPC based computers and is designed to meet the needs of both the casual and the professional programmer alike. It provides standard debugging capabilities, such as breakpoints and variable display, and includes advanced features like source language, context sensitive, expression analyzers, dynamic windows, and execution profiling. It fully supports Absoft Fortran 90/95, FORTRAN 77, C, and C++, as well as the Apple implementation of the C programming language and the Apple PowerPC assembler.

A debugger is a fundamental programming tool that is used to achieve a specific end. Fx is extremely easy to use and operates just like any other program for the Macintosh. There are no special graphical conventions to learn or Command and Option key sequences to remember. Fx commands do exactly what you expect them to. The depth of detail presented in the debugger is completely within your control.

How To Use This Chapter This chapter has been designed to allow you to obtain the specific information you will need for effective debugging as quickly as possible. The following descriptions of the remaining sections will direct you to the sections necessary for your particular needs. • Preparing For Debugging This section begins by describing how to compile and link your program with symbolic debugging information and start a debugging or profiling session. It also describes how to set breakpoints, single step, examine variables, and quit the debugger. Experienced programmers will find all the information they need in this section. • Debugging Concepts This section is designed for the less experienced programmer and presents basic debugging concepts such as using breakpoints and single stepping through programs. It also describes how to isolate problems in your program and get the most out of a debugging session • Fx Menus and Windows This section discusses in detail the Fx menu commands and the windows that they control. Every Fx command is described in this section.

Fortran User Guide 228 Using the Fx Debugger

• Profiling This section describes how to compile and link your program for profiling, use Fx to gather execution statistics, and how to use the information that is collected to analyze program execution.

PREPARING FOR DEBUGGING This section describes how to prepare your program for debugging with Fx and how to begin a debugging session. It also introduces the use of breakpoints, single stepping, and examining variables.

Source level debugging with Fx (or any debugger) requires that the symbolic information contained in the original source file be available to the debugger. Normally, this information is used only by the compiler during the early stages of parsing and lexical analysis and then discarded after the object file has been created. Preparing a program for debugging consists primarily of setting the required compiler and linker options to create a file that preserves the symbol and line number information.

NOTE: Only desktop applications, with or without MRWE, can be debugged with Fx. It is not possible to use the debugger on MPW tools.

Compiler Options

Use the -g option with the Absoft Fortran 90/95 and FORTRAN 77 compilers (the Debug with Fx checkbox in the main commando dialog) to direct the compiler to add symbol and line number information to the object file. This option must be enabled for each source file that you will want to have the source code displayed for while debugging. It is not required for files that you are not interested in.

Fortran User Guide Using the Fx Debugger 229

Figure 10-1 Fortran compiler option

Use the -g option with Absoft’s C/C++ compiler (the Debug with Fx checkbox in the commando dialog) to direct the compiler to add symbol and line number information to the object file. This option must be enabled for each source file that you will want to have the source code displayed for while debugging. It is not required for files that you are not interested in.

Figure 10-2 C compiler option

Fortran User Guide 230 Using the Fx Debugger

It is recommended that all optimization options be disabled while debugging. This is because the optimizers can greatly distort the appearance and order of execution of the individual statements in your program. Code can be removed or added (for loop unrolling), variables may be removed or allocated to registers (making it impossible to examine or modify them), and statements may be executed out of order.

Linker Options

The -sym on option (the Symbolic Output checkbox in the Debug Information… commando dialog) must be added to the command line for the Absoft linker, lnk. If you are using the commando dialog for the compiler, this will be done automatically. If you have created a Build script, you should add the option to the command line for lnk.

Figure 10-3 Linker option

The symbol file created by the linker with have the same name as the application with the characters .FxSYM appended to the end.

Size(-1) Resource

An application must have a SIZE(-1) resource with the canBackground flag set in order to be debugged. The flag can be set with a resource editor such as ResEdit, or by using the resource compiler tool, Rez, that is provided in the MPW environment. An example SIZE resource is presented below:

resource 'SIZE' (-1) { dontSaveScreen, acceptSuspendResumeEvents, enableOptionSwitch, canBackground, multiFinderAware, backgroundAndForeground, dontGetFrontClicks, ignoreChildDiedEvents, not32BitCompatible, reserved, reserved, reserved, reserved,

Fortran User Guide Using the Fx Debugger 231

reserved, reserved, reserved, * 64, * 48 };

System Folder Additions Communication between Fx and the application being debugged is managed by a background process called PowerMac Debug Services. It must be launched before Fx can be used — if it is not already running Fx will report an error. You should place it in the Startup Items folder inside the System Folder where it will always be available when you want to begin a debugging session.

PowerMac Debug Services also requires the system extension, PPCTraceEnabler, in order to allow Fx to place the PowerPC chip into trace or single step mode. This extension is an integral part of System 7.5 and later, but must be placed in the Extensions folder of the System Folder for System 7.1.

Note: The necessary files are normally placed in the required folders of the System Folder during the installation process.

Starting A Debugging Session Fx is launched just like any other Macintosh application in one of the following ways: • double-click on the Fx icon • select the Fx icon and choose Open from the Finder’s File menu • drag the icon of the symbol file onto the Fx icon • double-click on the icon of the symbol file

If you launched Fx by either of the first two methods, then from the File menu, choose Open… to select the symbol file of the application that you wish to debug.

After Fx reads the symbol file and loads your application, it will execute it’s initialization code, and leave it ready for debugging at the first executable statement of the main program.

Fortran User Guide 232 Using the Fx Debugger

You can execute statements one-at-a-time by selecting the Step Into or Step Over commands from the Control menu. Step Into will follow subroutine calls and function references, while Step Over will treat them as a single statement. The Return command, also in the Control menu, will execute all of the remaining statements in a procedure as though they were a single statement and return you to the point of the call. The Run To command will execute all of the statements up to line currently selected in the source code window.

Breakpoints are set by moving the cursor to the left of the vertical gray line in the source window where the line number display is maintained and clicking the mouse button. The letter B will appear, indicating a breakpoint at that line number. Clearing a breakpoint is accomplished by simply clicking the mouse button on any line number where a breakpoint is set. Also, breakpoints may be temporarily disabled without clearing them by clicking the mouse button on the letter B. The letter D will be displayed as long as the breakpoint is disabled.

Holding down the Option key while setting a breakpoint brings up the breakpoint control dialog which allows you set skip counts and special conditions which must be met before a breakpoint takes affect. Holding down the Option key while clicking on a line number executes the Run To command in the Control menu.

Variables can be examined in several ways. The easiest method is to simply select a symbol name or address expression in the source code window and then choose Print “” from the Actions menu. Any selection made in the source window is automatically inserted between the quotation marks. If the variable is a pointer, selecting Print * “” will dereference the symbol and display the value that is pointed to.

The Print As… selection in the Actions menu allows you to directly enter the name of any symbol or address expression in the current procedure that you wish to examine. Whereas the Print “” and Print * “” commands will only display variables in a format consistent with their type, the Print As… command allows you to select the display format.

The Watch “”, Watch * “”, Watch As… and Watch Locals commands operate the same as the associated print commands, but continuously update the value display as you step through the program.

Fortran User Guide Using the Fx Debugger 233

DEBUGGING CONCEPTS This section is intended for the less experienced programmer and presents basic debugging concepts such as single stepping through programs and using breakpoints. It also describes how to isolate problems in your program and get the most out of a debugging session

Getting Started Before beginning this section, you should be familiar with the information presented in the previous section, Preparing For Debugging. It describes how to compile and link your program and how to start a debugging session. After Fx has been launched and you have opened the application for debugging, a source code window is displayed similar to the one shown below:

Figure 10-4 Source code window

Positioned at the top of this window are two pop-up menus — a file menu on the left and a procedure menu on the right. The file menu contains a list of all of the files that were used to build the application and is available for easily accessing the various files they comprise the source code to the program. Initially, Fx will only look for source files in the folder where the application was launched. If the source code is maintained in multiple folders, use the Add Path command in the File menu to add additional folders to the search path.

Located to the right of the file menu, the procedure menu lists all of the procedures (functions and subroutines) in the current source file.

Also at the top of this window, to the right, is a box which indicates the current line number — the line number where the program is stopped.

Fortran User Guide 234 Using the Fx Debugger

The gray vertical line divides the text window into two sections. The section on the right is the source code for the current procedure. Text, such as variable names and address expressions, can be selected in this window and displayed using one of the commands like Print or Watch in the Actions menu. If a procedure name is selected, you can use the Set Breakpoint On “” command in the Actions menu to set a breakpoint there or the Code For “” command in View menu to display its source code. The Run To command in the Control menu will execute all of the statements up to the source code line currently selected in the window.

The section to the left of the gray vertical line shows the line number of every line in the source file — comment, declaration, and executable. Executable statements are further denoted with a small diamond to the far left indicating that a breakpoint (see below) may be set on that line. The current line, the line where the program is stopped, is marked the characters: =>.

When the cursor or mouse pointer is moved into the region to the left of the gray vertical line it changes into a pointer with a larger diamond. This indicates that breakpoints may be set or cleared as described later in this section in USING BREAKPOINTS.

Single Stepping Single stepping means to execute one line of a program and then stop at the beginning of the next line. If the line contains more than one executable program statement, they are all executed as one. If a statement is continued across multiple lines, they are all treated as one and execution stops on the line after the last continuation line.

When a line contains a subroutine call or a function reference, you can decide whether to follow the procedure reference or to simply treat it as a single statement. If you are certain that the procedure is correct, you can Step Over the reference and allow all of the statements in it to execute as one. If, on the other hand, you are suspicious of the routine in question, you can choose to Step Into it, following the flow of execution. If you change your mind, the Return command in the Actions menu will execute all of the remaining statements in the procedure automatically and return you to the calling procedure.

Using Breakpoints Single stepping through a long program can be very tedious, especially if the program contains many loops or loops that iterate many times. It is far more efficient to allow the program to execute normally until it reaches a point where you want to take a closer look at exactly what it is doing. Breakpoints are the solution. A breakpoint is a location in a program, determined by you, where execution stops. You simply set a breakpoint at the location in your program that you are concerned with and let the program run normally. When it reaches the breakpoint, it will stop and leave you in full control with the debugger.

Fortran User Guide Using the Fx Debugger 235

Setting a breakpoint with Fx is extremely easy — you just point to the line number with the mouse and click the mouse button. Once a breakpoint has been set, the letter B replaces the diamond, indicating that a breakpoint has been set on that line.

Figure 10-5 Setting a breakpoint

To clear a breakpoint, you do exactly the same thing — point to a line number with a breakpoint set on it, click the mouse button, and the letter B is replaced with the original diamond.

Breakpoints may be temporarily disabled without removing them by clicking the mouse button with the pointer positioned directly over the letter B itself — the letter B will change to a D, indicating that the breakpoint is disabled. Disabled breakpoints are enabled again by performing the same operation on the letter D.

To give you further control over execution, you can set more conditions than just reaching the line where the breakpoint is set before stopping execution. This is very important if your program must execute the same statement many times before you are interested in stopping it. Additional conditions are placed on breakpoints in the breakpoint control dialog. There are two ways to bring up the breakpoint control dialog:

• Hold down the Option key when you click the mouse button on the breakpoint indicator. or: •Use the Breakpoints command in the Windows menu

Fortran User Guide 236 Using the Fx Debugger

If you use the Breakpoints command in the Windows menu, you double-click on the breakpoint that you are interested in to bring up the breakpoint control dialog (see Breakpoints section in the Fx Menus and Windows section later in this chapter).

The breakpoint control dialog appears as follows:

Location can be expressed as either a file name and line number for source code, or as an address for assembly language. Skip Count determines the number of times that this statement must execute before stopping for the breakpoint. Condition is a logical expression stated in the source language of the file that contains the line. The condition, if present, must be met in order for the breakpoint to be taken. For example, consider the following Fortran program fragment:

DO 100 I=1,1000 C = SQRT((A(1)-B(1))*(A(1)-B(1)) + & (A(2)-B(2))*(A(2)-B(2)) + & (A(3)-B(3))*(A(3)-B(3))) CALL NEWLOC(A,B,C) 100 CONTINUE

If you want to stop only if the value of C becomes greater than 100.0, set a breakpoint on the second line and set the condition to:

C .GT. 100.0

This dialog can also be used to temporarily disable a breakpoint without deleting it by clicking on the Disabled radio button.

The One Time check box causes the breakpoint to be removed the first time execution stops at the line it controls.

Displaying Variables Fx displays information about program variables in a special window type called the Symbols window. The easiest way to open a Symbols window to display a variable is to select the name of the variable in the source code window and issue the Print “” command

Fortran User Guide Using the Fx Debugger 237

from the Actions menu. Fx inserts whatever is selected in the front-most window between the quotation marks in the various print and watch commands in the Actions menu.

The Symbols window is normally divided into two panes — symbol names to the left and values to the right. If a symbol is a pointer, double-clicking on its name dereferences it — that is its value will be used as the address of the variable. If the variable is an aggregate such as an array, structure, record, union, class, etc., its value is printed as the aggregate type enclosed in brackets: , , , etc. The elements of the variable are displayed by double-clicking in the value field. An additional pane, indicating the data type of the variable, can be added to the left of the symbol name with the Types command in the View menu as shown here:

Figure 10-6 Symbols window with a Type pane

The width of these panes can be adjusted as necessary by moving the mouse pointer to the title row, placing it over one of the vertical lines (where the cursor will change shape), and then dragging the line to a new position.

By default, values are displayed in a format consistent with the data type of the variable. There are two ways to force the display of values in a different format. If the variable is already displayed in the Symbols window, select its name and use the View As… command in the View menu to specify a different display format. You can also choose the Print As… command from the Actions menu to enter the variable name and select a specific display format.

The mouse, tab key, or arrow keys may be used to navigate through the list of variables in a Symbols window. Holding down the Option key while pressing either the right or left arrow keys will move to the next column rather than the next character. Holding down the Option key while pressing either the up or down arrow keys will move to the first or last column in the current row respectively. Holding down the shift key while pressing the tab key will move to the previous variable.

If a symbol is an array, its value is printed as the string as mentioned above. Double-clicking in the value field of an array opens a new Symbols window displaying the individual array elements up to the limit specified in the Array Size field of the

Fortran User Guide 238 Using the Fx Debugger

Preferences… dialog which is found in the Edit menu (see the Preferences section). This is reasonable for small arrays of no more than 100 elements or so, but is obviously not appropriate if you are trying to display and then scroll through a 200 by 200 matrix. Constraints on the section of the array to be displayed can be established with the Dimension Array Bounds dialog which is invoked by holding down the Option key when you double-click in the value field of an array. If you prefer, you can force this dialog to always be invoked by checking the Always show dialog when printing arrays box in the Preferences… dialog in the Edit menu (see the Preferences section).

The Dimension Array Bounds dialog allows you to specify the lower and upper bounds of each dimension in the array that you want to display as seen in the following figure:

Figure 10-7 Dimension Array Bounds Dialog

The lower and upper bounds will default to the full dimension extent as it was established in the declaration statement for the variable in the source code. Dimensions beyond the original declaration are disabled (grayed out) and no values can be entered in those fields. The total number of array elements selected is displayed as Number of Elements after the dimension bounds data entry boxes.

Fortran User Guide Using the Fx Debugger 239

The Format… button brings up the standard format dialog allowing you to specify a display format other than the default for the data type of the array. Two dimensional arrays can be displayed in a special spread-sheet like window by clicking on the Matrix button in the 2D Array Display Format section:

Figure 10-8 Matrix display

Note: Displaying more than one thousand array elements dynamically with the Watch All command may cause degradation in the performance of Fx or program failure due to insufficient memory.

All of the variables in a subroutine or function can be displayed at once using the Locals command from the View menu. This command limits the display to those variables that have function scope. Scope means the range within a program that a variable is visible or known. For Fortran programs, the only scope available is local. Fortran variable names, even those in common blocks, are never visible outside of the subprogram that they are declared in. For C language programs, scope can be global, local, or static, meaning the entire program, the current function, or the current file, respectively. The Globals and Statics command in the View menu are dimmed when debugging Fortran files.

The variable display commands described up to this point only print the current value of the variable. Continuing the program or executing further statements will probably cause the value to change, but since that change will not be reflected in the Symbols window, the display is said to be static. A dynamic or continually updated display of variables is available with the Watch commands in the Actions menu. The watch commands are issued in same manner as the print commands. If the value of a dynamically updated variable changes as the result of the execution of a program statement, the change will be indicated in the Symbols window by a change in color of the value field. The Watch All command changes a Symbols window from static to dynamic, causing all variables in the window to be continuously updated.

Fortran User Guide 240 Using the Fx Debugger

Changing Variables The value of any program variable may be easily modified or changed by entering the new value (or portion thereof) as an expression in the value field for the variable and then pressing the Return or Enter key. Only after the Return or Enter key is pressed is the new value accepted. If you change your mind, simply click the mouse button anywhere else on the screen and the variable will revert to the original value.

The value of a machine register that has been printed in the Symbols window may be changed in a similar manner.

The standard text editing commands may be used in the value field to facilitate variable modification.

Debugging Hints Fx cannot debug your program for you, but it can provide you with the information necessary to track down programming errors and logic faults. The key to gaining that information is asking the right questions. This section highlights some general guidelines and tips for getting the most out of a debugging session.

• If a program gives different results each time it is run, look for uninitialized variables and local variables that are being overwritten. Remember that local variables must declared in a SAVE statement in Fortran and with a static specifier in the C programming language in order to retain their definition status across procedure references.

• You can display the values of the local variables in a previous referencing procedure by changing the current frame in the Stack window as described in the Control section.

• If you find yourself in a procedure that you are not interested in, use the Return command in the Control menu to return immediately to referencing procedure. This command will execute all of the remaining statements in the function or subroutine and return you to point where it was referenced.

• If the value returned by a function is completely wrong, yet single stepping through the function itself seems to calculate the result correctly, check the function declarations and definitions. Also, incorrectly typing the precision of a floating point function produces incorrect results due to the different internal representations of single and double precision numbers.

• If you are experiencing difficulty with Macintosh toolbox functions, pay particular attention to the data types and method of passing parameter lists to the routines. The VAL function must be to used when passing a parameter by value in Fortran and a Universal Procedure Pointer must be used in any language to pass the address of call-back routine.

Fortran User Guide Using the Fx Debugger 241

• Finding an obscure problem in a large program can be tedious and time consuming, especially if the program crashes. Try single stepping over calls to large subroutines and functions until the program fails. It is much easier to examine a problem more closely once you have isolated the problem to an individual procedure.

• Pointers are a powerful programming feature in any computer language, but they can also cause a tremendous amount of havoc when they are not initialized correctly or when they unexpectedly lose their definition status. In both cases, using null or dangling pointer usually leads to disaster. Incorporating pointers in your routines requires a defensive programming style.

FX MENUS AND WINDOWS This section describes the menu selections that are used to perform Fx commands and the windows that they control. The name of the command is given, followed by its Command-key equivalent (if any) and a description of its function.

File Menu

The File menu contains commands for creating new source and assembly language windows, opening application and symbol files, adding paths for source directories, closing individual windows, and quitting Fx.

New Source (aN)

The New Source command is used to create additional source file and assembly language windows. These additional windows may be used to display various portions of the program in separate windows during a debugging session. New Assembly is shown in the menu when the front-most window is an assembly language display. The Code menu selection in the Windows menu (described below) can be used to select a file or a procedure to be displayed in the current window.

Open… (aO)

This command is used to select an application for debugging. A standard file selection dialog box is displayed to choose the symbol file for the application. The symbol file is created by the linker and will have the same name as the application with the characters .FxSYM appended to the end. After the application’s symbol file is chosen, a source code window is opened and positioned at the entry point of the program.

Open Workspace…

This Open Workspace command is used to select a previously Fx session.

Fortran User Guide 242 Using the Fx Debugger

Add Path…

The default search path for locating source files for the application being debugged is the folder where the application and its symbol file were loaded. Since all of the source for an application may not reside in the same folder, the Add Path command is used to add directory paths to the search list for the other source files that were used to build the application.

Close (aW)

This command closes the front-most window. Holding the Option key down adds the following functionality depending on the window type:

• If the front-most window is a Symbols window, the command becomes Close All Symbols.

• If the front-most window contans a string variable, the command becomes Close All Strings.

• If the front-most window is any other window, the command becomes Close All.

Save Workspace

Use this command to save the current Fx session. The saved components include the program and .FxSym paths, open windows and their positions, and breakpoints.

Save Window Positions

This command saves the front-most window positions and sizes as the new default for Fx.

Quit (aQ)

The Quit command exits Fx and returns you to the Finder. If necessary, Fx will automatically stop and kill the application (see Stop and Kill in the Control menu below) before exiting.

Edit Menu

The Edit menu contains the standard text editing commands for cutting, copying, pasting, and clearing text. It is not possible to cut, paste, or clear text in an Fx source code or assembly language window. However, text can be selected, copied, and pasted into text windows opened by other applications. Text cannot be pasted into the text-edit boxes of Fx dialogs.

Fortran User Guide Using the Fx Debugger 243

Undo (aZ)

This command is not used by Fx, but is placed in the Edit menu for any desk accessory that may use it.

Cut (aX)

This command can be used to remove selected text from the front-most window of various applications and place it onto the Clipboard.

Copy (aC)

The Copy command duplicates selected text from the front-most window onto the Clipboard. Text on the Clipboard may be pasted into editable windows opened by other applications.

Paste (aV)

This command can be used to paste copied text, such as variable or procedure names into editable windows opened by other applications.

Clear

Similar to Cut, this command removes the selected text from the front-most window but does not place a copy on the Clipboard. The Clipboard remains unchanged.

Select All (aA)

Use this command to select all of the text in the front-most window.

Preferences

This dialog consists of the three separate panes that are selected from the drop down menu. The selections are: Environment, Format, and Startup.

Environment

Fortran User Guide 244 Using the Fx Debugger

Selecting Ignore file modification dates will suppress the warning messages issued when a source file has been modified since the program you are debugging was created.

Selecting Ignore unlocatable file errors will suppress the warning messages issued when a source file can not be found.

Selecting Prompt for symbol file at startup will cause Fx to automatically request a symbol file when it is launched.

Selecting Fold all symbolic names to lower case will cause Fx to convert all variable names to lower case before searching your programs symbol table.

The Always show dialog when printing arrays selection causes Fx to automatically invoke the array parameter display options dialog when an array name is double-clicked without the requirement to hold down the Option key.

Format

Fortran User Guide Using the Fx Debugger 245

Selecting Show types in Symbol windows by default will make displaying the types of variables and expressions in Symbol windows the default behavior.

Selecting Show C++ method names followed by class will reverse the order of C++ member and class names in the Code window.

Use the Display function relative assembly addresses checkbox to show assembly language addresses as offsets from function names in addition to absolute addresses.

Selecting Show all available source files displays all files containing debugging information in the file menu of source code windows and the Code window—not just those files comprising the application. This allows for easier symbolic debugging of DLLs.

Use the Font SIze box to specify the size of the text displayed by Fx.

The Tab Size text field is used to specify the size of tabs for source files which do not have recognizable tabsize information stored in their resource forks.

The Array Size text can is used to specify the number of array elements Fx will show when an entire array is displayed in a Symbol window.

Startup

This Preferences dialog allows you to control where the debugger stops after startup. This is particularly useful when debugging Windows applications where the entry point is WinMain, rather than the usual main. The debugger will search the list from top down until a valid entry point is found.

Fortran User Guide 246 Using the Fx Debugger

Control Menu

The Control menu is used to control the execution of the application being debugged with Continue, Stop, Return, Step Into, and Step Over commands. This menu also contains commands that can manipulate the stack frame for selecting which procedure is the current one for examining source code and assembly language and the values of local variables: Down, Home, Up, and Show Program Counter.

These are the most commonly used Fx commands and all but Stop and Clear All Breakpoints have command key equivalents.

Continue (aJ)

Use this command to start or continue execution of the application. The application will execute until a breakpoint is encountered or execution is suspended in some other manner (such as switching the application with the menu on the far right side of the menu bar).

Kill (aK)

The Kill command stops the application and removes it from memory.

Stop

The Stop command stops execution of an application the next time it calls WaitNextEvent and displays the source code and/or assembly language associated with the current location of the program counter in the source code window.

Note: If the application does not call WaitNextEvent again, the Stop command will have no effect.

Restart

The Restart command stops the application and re-executes it from the startup entry point.

Return (aR)

This command is used to automatically execute all of the remaining statements in the current subroutine or function and return to the statement (source code and/or assembly language) immediately following the point where it was referenced in the calling procedure.

Fortran User Guide Using the Fx Debugger 247

Step Into (aI)

The Step Into command is used to execute individual source code or assembly language statements. If a subroutine call or a function reference is encountered, the current code display window changes to that procedure and execution stops there. If symbol information is not available for the procedure, an assembly language window will be opened for it (see the Assembly command in the Windows menu below). When source line information is available, this command executes source statements by default and single instructions when the Option key is held down. If source information is not available, it always executes single instructions.

Step Over (aS)

Similar to the previous command, the Step Over command is also used to execute individual source code or assembly language statements, but it treats subroutine calls and function references as though they were single statements. When source line information is available, this command executes source statements by default and single instructions when the Option key is held down. If source information is not available, it always executes single instructions.

Run To (aT)

The Run To command will execute the program until it gets to the line currently selected in the source code or assembly language window or until a breakpoint is encountered

Down (a [)

The Down command changes the display in the source code and/or assembly language window to that of the next referenced procedure. For example, if a procedure called function1 is displayed in the source code window and it references a procedure called function2, the Down command will display the source code for function2.

This command also changes the local symbol scope to that of the displayed procedure allowing you to examine the variables associated with the procedure.

If a stack trace window has been opened (see Stack in the Windows menu below), the Down command will highlight the next procedure down the window and display its parameter list (its arguments).

Home (aH)

Use this command to return the source code and/or assembly language display to the bottom of the stack frame.

This command also changes the local symbol scope to that of the displayed procedure.

Fortran User Guide 248 Using the Fx Debugger

If a stack trace window has been opened (see Stack in the Windows menu below), the Home command will highlight the current procedure and display its parameter list (its arguments).

Up (a])

The Up command changes the display in the source code and/or assembly language window to that of the previous referencing procedure. For example, if a procedure called function2, which was referenced by a procedure called function1, is displayed in the source code window and the Up command is given, the source code for function1 will be displayed.

This command also changes the local symbol scope to that of the displayed procedure allowing you to examine the variables associated with the procedure.

If a stack trace window has been opened (see Stack in the Windows menu below), the Up command will highlight the next procedure up the window and display its parameter list (its arguments).

Clear All Breakpoints

Use this command to clear all of the breakpoints in the application.

Show Program Counter (aP)

Use the Show Program Counter command to return the source code display to the current location in the application. The current location is the statement in the program where execution stopped.

Unlike the Home command, this command does not switch stack frames.

View Menu

The commands in the View menu are used to change the location of the display in source file and assembly language listings, open variable display windows, change the value of a specified variable, change the format used to display a variable, and go directly to the source code for specified procedure.

The Globals, Locals, and Statics commands all display variables in the same window — the Symbol window. The difference is in the scope of the variables displayed. Scope means the range within a program that a variable is visible or known. For Fortran programs, the only scope available is local. Fortran variable names, even those in common blocks, are never visible outside of the subprogram that they are declared in. For C language programs, all three scopes are available as described below.

Fortran User Guide Using the Fx Debugger 249

Address…

To go directly to a specific address in an assembly language listing without scrolling, use the Address… command.

Line…

To go directly to a specific line in a source file listing without scrolling, use the Line… command.

Next (a9)

Displays the next screen full of assembly language instructions for the function visible in the Assembly window.

Prev (a0)

Displays the previous screen full of assembly language instructions for the function visible in the Assembly window.

Globals

The Globals command displays a list of all of the variables with application scope in the Symbols window. The Symbols window is first opened if one does not exist. For Fortran debugging, all variables are considered local and the Globals menu selection is dimmed.

Locals

The Locals command displays a list of the local variables in the current procedure in the Symbols window. The Symbols window is first opened if one does not exist. For Fortran debugging, all variables are considered local — even variables in common blocks since their names have only local scope. For C debugging, local variables are those with only function scope.

Fortran User Guide 250 Using the Fx Debugger

Statics

The Statics command displays a list of all of the variables with file scope in the Symbols window. The Symbols window is first opened if one does not exist. For Fortran debugging, all variables are considered local and the Statics menu selection is dimmed.

Types

Use this command to toggle the display of a data type pane in the Symbols window.

Change…

This command is only available if a variable name is highlighted in the Symbols window. Selecting the Change… command opens the change variable dialog for assigning a new value to the variable:

The new value can be entered as an expression in the source language of the variable.

Note: The value of any variable type other than a string can be changed directly in the Symbols window by entering the new value in the value field and pressing Return or Enter.

View As…

Use this command to control the format of the value display of the variable whose name is highlighted in the Symbol window.

Code For “”

To go directly to the source code and/or assembly language for a procedure name selected in any text edit pane without scrolling or using the Code command in Windows menu, use the Code For “” command.

Fortran User Guide Using the Fx Debugger 251

Actions Menu

The Actions menu is used for finding strings in a source code window, printing the values of variables and address expressions, and setting breakpoints on selected procedure names. The Print commands display the current value of the specified variable or address expression each time the command is given, maintaining a history of the values. The Watch commands update the value display each time the program stops, either by single stepping or by reaching a breakpoint. Values can be displayed by selecting strings in the source code window or by directly typing address expressions into dialog boxes.

Find… (aF)

The Find… command opens a dialog for entering a string that is then searched for in current source code window. The Find… command is case sensitive.

Find Again (aG)

Use this command to find the next occurrence of the string specified with the Find… command.

Print “” (aE)

The Print “” command displays the value of the variable or address expression currently selected in the source code window. The value is displayed in a format appropriate for its data type. To display the value in other formats, use the Print As… command described below or the View As… command in the View menu, described earlier.

Print * “” (aD)

If the symbol or address expression that is selected in the source code window is a pointer variable, choose the Print * “” command which will first dereference the variable before displaying it. The value is displayed in a format appropriate for its data type. To display the value in other formats, use the Print As… command described below.

Fortran User Guide 252 Using the Fx Debugger

Print As…

The Print As… command is used to display the value of any variable in the current procedure in any format required. The command displays a dialog box where the format of the output is selected and the name of variable is entered.

Watch “”

The Watch “” command displays and continuously updates the value of the variable or address expression currently selected in the source code window. The display is updated each time the program stops, either at a breakpoint or after a single step. The value is displayed in a format appropriate for its data type. To display the value in other formats, use the Watch As… command described below.

Watch * “”

If the symbol or address expression that is selected in the source code window is a pointer variable, choose the Watch * “” command which will first dereference the variable before displaying it. Thereafter, it will be continuously updated each time the program stops, either at a breakpoint or after a single step. The value is displayed in a format appropriate for its data type. To display the value in other formats, use the Watch As… command described below.

Watch All

Use the Watch All command to continuously update the value display of all of the variables in the Symbols window. This command is dimmed if the Symbols window is not the front-most window.

Fortran User Guide Using the Fx Debugger 253

Watch As…

The Watch As… command is used to continuously display the value of any variable in the current procedure in any format required. The command displays a dialog box where the format of the output is selected and the name of variable is entered. Thereafter, the value is updated each time the program stops, either at a breakpoint or after a single step.

Watch Locals

Use this command to display the arguments and local variables of the current stack frame dynamically.

Set Breakpoint On “”

The Set Breakpoint On “” command establishes a breakpoint at the entry point of the procedure that is currently selected in the source code window.

Profile Menu This menu is used to configure the various profiling parameters as described in the section Profiling With Fx and to enable or disable profiling. The best profiling results are obtained when the program is compiled with the -p option.

Configure…

This command is used to configure the profiler. Refer to the section Profiling With Fx for details on this command.

On

This toggle command turns profiling on (or off). Refer to the section Profiling With Fx for details on this command.

Fortran User Guide 254 Using the Fx Debugger

profmt…

This command launches the program used to display profile statistics. Refer to the section Using Profmt for details on this command.

Windows Menu This menu is used to open windows for displaying additional information such as assembly language listings, memory dumps in various formats, the PowerPC 601 register values, and stack frame traces. There are also menu selections available for selecting source code and class browsers. If the particular window is already open, the command will bring it to the front. As Source, Assembly, and Symbol windows are opened, their names will be appended to the bottom of this menu, making it easy to bring a particular window to the front.

Hide Toolbar/Show Toolbar

Use the Hide Toolbar/Show Toolbar command to toggle the display of the palette containing Step Into, Step Over, Return, Continue, and Kill command equivalents.

Tile

Use this command to tile all of the open debugger windows on the desktop.

Cascade

The Cascade command is used to arrange multiple open debugger windows in a overlapped or cascaded manner.

Assembly (a1)

Use the Assembly command to display an assembly language listing of the application being debugged. A window will be opened at the location in memory of the current program counter. The text marked by bars on the left side of the listing represents the machine code for the current high level language statement. The Address… menu selection in the View menu can be used to go directly to a memory address in the assembly listing.

All of the Control menu commands, such as Continue, Step Into, and Step Over, are available in an assembly language window, but it is not possible to single step through Apple ROM code.

Fortran User Guide Using the Fx Debugger 255

Breakpoints (a2)

The Breakpoints command opens a window listing all of the breakpoints that have been set in the application.

Each line lists the file and line number where the breakpoint is set, whether it is currently enabled or disabled, the current count and the skip count (in parentheses), and the condition. The skip count determines the number of times this statement must execute before stopping and the current count is the number of times the statement has been executed already without stopping. The condition is a logical expression stated in the source language of the file. The condition, if present, must be met in order for the breakpoint to be taken. For example, consider the following program fragment:

DO 100 I=1,1000 C = SQRT((A(1)-B(1))*(A(1)-B(1)) + & (A(2)-B(2))*(A(2)-B(2)) + & (A(3)-B(3))*(A(3)-B(3))) CALL NEWLOC(A,B,C) 100 CONTINUE

If you want to stop only if the value of C becomes greater than 100.0, set a breakpoint on the second line and set the condition to:

C .GT. 100.0

Fortran User Guide 256 Using the Fx Debugger

Selecting an individual breakpoint in this window by double-clicking on it opens the breakpoint control dialog:

This dialog can be used to set or modify the location — expressed as either a file name and line number for source code, or as an address for assembly language. The condition and the skip count may also be set or modified, as well as whether the breakpoint is enabled or disabled

Classes (a3)

The Classes command opens a window displaying the names of all the classes visible in the current scope, along with a list of their member functions and a graphical representation of their inheritance hierarchy. Selecting a class name in the left pane will display its member functions in the right pane. Double clicking on the name of a member function will display it’s source code. A breakpoint can be set on the member function by selecting its name and using the Set Breakpoint On command in the Action menu. Clicking on a class name in the inheritance pane selects it in the class list and shows its member functions.

Fortran User Guide Using the Fx Debugger 257

Code (a4)

Use this command to open a file browser window. The code window is divided into two panes:

The left pane is a list of the files that comprise the application. Selecting one of these file names causes the procedures that are contained within it to be displayed in the right pane. If you double click on a procedure name it will be displayed at the first executable line in the front-most window. (Use the New Source command in the File menu to create a new source code window.)

You may need to use the Add Path… command in the File menu if the source file is not located in the same folder as the application.

Memory (a5)

This command is used to directly examine memory by specifying an address rather than the symbolic name of a variable. The Memory command displays the following dialog:

Location specifies the memory address to examine (hexadecimal numbers should be entered as 0xnnn). The format and size are controlled with radio buttons as shown.

Fortran User Guide 258 Using the Fx Debugger

Registers can be specified as addresses by entering them as they appear in the Register window (see below). Clicking on the OK button produces a window similar to the one shown below:

General Registers (a6)

The General Registers command opens a window which displays the contents of the PowerPC registers, as well as the program counter and the condition code bits. This window is updated after every single step command and whenever breakpoints are encountered. The value of a register can be changed by selecting the register, printing it in a Symbols window, and entering a new value in the value field.

Fortran User Guide Using the Fx Debugger 259

FPU Registers

The FPU Registers command opens a window which displays the contents of the PowerPC floating point registers. This window is updated after every single step command and whenever breakpoints are encountered. The value of a register can be changed by selecting the register, printing it in a Symbols window, and entering a new value in the value field.

Stack (a7)

The Stack command opens a window which displays a trace of the stack frame. The current procedure is highlighted:

The window displays a list of the procedures in the current call chain, starting with the first or oldest at the top of the pane and descending to the last or newest at the bottom. The name of the source file containing the procedure and the current line number in the file is also displayed.

Symbols (a8)

This command brings the Symbols window to the front.

Fortran User Guide 260 Using the Fx Debugger

PROFILING This section describes how to prepare a program for profiling, how to use Fx to gather execution statistics, and then how to use Profmt, a separate program, to analyze the information that is collected.

Options For Profiling The following two sections discuss the options that are given to the compiler and the linker when you are preparing a program for profiling.

Compiler Options

The -p option (the Profiler Information checkbox in the Compiler Control… commando dialog) is used with either Absoft Fortran 77 or Absoft C/C++ to direct the compiler to add code to the compiled program which counts the number of times a particular procedure (subprogram or function) is called.

Figure 10-9 Fortran compiler option

This option can be used in conjunction with any other option or set of options, including optimization. The -g compiler option is not necessary and probably should not be used since it prevents the compiler from performing certain optimizations that may be important to the execution speed of the program.

Note: A program compiled without the -p option can still be profiled, but you will learn only the amount of time spent in an individual procedure, not the number of times it was called, and therefore, not how long it takes to execute per call.

Fortran User Guide Using the Fx Debugger 261

Linker Options

The -sym on option (the Symbolic Output checkbox in the Debug Information… commando dialog) must be added to the command line for the Absoft linker, lnk, to produce a symbol file containing information on the entry points of the program. If you are using the commando dialog for the compiler, this will be done automatically when you select the -p option as described above. If you have created a Build script, you should add the option to the command line for lnk.

Figure 10-10 Linker option

The symbol file created by the linker with have the same name as the application with the characters .FxSYM appended to the end.

Note: It is not necessary to compile the program with the -g compiler option for the linker to produce a symbol file containing program entry points. The -g option is only required when symbolic information on program variables is needed which is not the case when profiling.

Profiling With Fx

Fortran User Guide 262 Using the Fx Debugger

To profile a program, begin by launching Fx in the normal manner as described in the section Starting A Debugging Session earlier in this chapter. After the program and the symbol table have been loaded, select the Configure… command from the Profile menu:

Figure 10-11 Profile Configuration Dialog

The Save Profile Information As: text box is used to specify the name of the file in the current directory to which the profile statistics will be written. If you want the profile statistics to be written to a different directory, click on the Save As… button to bring up a standard file selection dialog box. The default is to write the statistics to a file named Profiler.Out in the current directory.

Use the Sample Rate: pop-up menu to indicate the granularity of profiling which is how often you want the profiler to examine the program counter. A smaller number means it will check more often, giving more accurate statistics, but increase the overall amount of time required to profile your program.

After you are satisfied with the configuration settings, click on the OK button and profiling will automatically be turned on. Begin profiling by selecting Continue from the Control menu and the various execution statistics will be gathered automatically as the program executes. When your program exits, the statistics can be examined with Profmt, described in the next section.

If you interested in profiling only a part of your program, the On/Off toggle command in the Profile menu can be used to control when statistics are accumulated. First, use the command to turn off profiling after you have set the configuration parameters, then set a breakpoint at the point you wish to begin profiling and execute to that point. When the breakpoint is reached, turn profiling back on again and continue execution.

Using Profmt

Profmt is a separate application for displaying the results of a profiling session and can be invoked directly from Fx by selecting profmt… from the Profile menu, or it can be launched from the desktop. Profmt contains four menus — the normal Apple menu as well as File, Edit, and Sort menus.

Fortran User Guide Using the Fx Debugger 263

The display is tabular in layout and consists of the name of each procedure followed by the number of calls to the procedure, the total amount of time, in tenths of seconds, spent in the procedure, the amount of time, in milliseconds, to execute the procedure once (time/call), and then a histogram determined by the current sort order established with the commands in the Sort menu. The -p compiler option is necessary for the calls or time/call information to be valid.

If the procedure name is displayed in boldface, the procedure has line number statistics associated with it. Click on the procedure name to open a new window displaying line oriented profile information about the procedure.

If the procedure name is displayed in plain text, holding the mouse button down while pointing on the line of data opens a pop-up window with more extensive statistics.

The following sections describe the menu selections that are used to perform Profmt commands.

File Menu

The File menu contains commands for opening and closing profile output files, displaying general information about the program, page setup and printing the output window, and quitting Profmt.

Open… (aO)

This command is used to select a profile output file for display. A standard file selection dialog box is displayed to choose the profile output file for the application. The profile output file is created by Fx and will have the default name of Profiler.Out, although you may give it any other name you choose. Only one profile output file may be displayed at a time.

Close (aW)

Use this command to close a profile output file so that another may be opened.

Info (aI)

Use this command to display general information and statistics about the profiled program.

Page Setup…

Use this command to make custom page choices for printing.

Print… (aP)

Use this command to print a profile display.

Fortran User Guide 264 Using the Fx Debugger

Quit (aQ)

The Quit command exits Profmt and returns you to the Finder.

Edit Menu

The Edit menu contains the standard text editing commands for cutting, copying, pasting, and clearing text. It is not possible to cut, paste, or clear text in Profmt. However, the menu selections are available for desk accessories that may need them. This menu also contains commands for editing the appearance of the profile display. All of the data elements displayed may be hidden or shown with the commands in this menu. The settings made from this menu are saved when a profile output file is closed and reestablished when it is reopened.

Undo (aZ)

This command is not used by Profmt, but is placed in the Edit menu for any desk accessory that may use it.

Cut (aX)

This command is not used by Profmt, but is placed in the Edit menu for any desk accessory that may use it.

Copy (aC)

This command is not used by Profmt, but is placed in the Edit menu for any desk accessory that may use it.

Paste (aV)

This command is not used by Profmt, but is placed in the Edit menu for any desk accessory that may use it.

Clear

This command is not used by Profmt, but is placed in the Edit menu for any desk accessory that may use it.

Hide Time

Use this command to hide (or show if already hidden) the column of values representing the total number of tenths of seconds spent in each procedure.

Fortran User Guide Using the Fx Debugger 265

Hide Calls

Use this command to hide (or show if already hidden) the column of values representing the total number of calls to each procedure.

Hide Time/Call

Use this command to hide (or show if already hidden) the column of values representing the time per call ratio. The time/call ratio is given in milliseconds per call.

Hide Graph

Use this command to hide (or show if already hidden) the histogram.

Sort Menu

The Sort menu is used to control the appearance of the data for visual analysis of the results of the profiling session. A list sorted by time alone may suggest that a particular procedure is inefficient, but when sorted by time/call, you find that although it is called thousands of times, it executes extremely quickly.

By Name

Use this command to sort the list of procedures in name order. The Ascending or Descending command (see below) can be used to set either increasing or decreasing order. When the list is sorted by name, the histogram represents time/call.

By Time

The By Time command sorts the list of procedures by execution time. The histogram represents the relative amount of the total time spent in each procedure.

By Calls

This command sorts the list of procedures by number of calls to each procedure. This information is only valid for those procedures compiled with the -p compiler option.

By Time/Call

Use this command to sort the list of procedures by the number of milliseconds spent in each procedure per call. This information is only valid for those procedures compiled with the -p compiler option. The histogram represents the relative amount of time taken to execute each procedure per call.

Fortran User Guide 266 Using the Fx Debugger

Ascending

Use this command to set the sort order (By Name, By Time, By Calls, or By Time/Call) to ascending or increasing order.

Descending

Similar to the previous command, the Descending command is also used to change the sort order, but to descending or decreasing order.

Fortran User Guide 267

Appendix A

Absoft Compiler Option Guide

This appendix summaries the options for the Absoft Fortran 90/95, FORTRAN 77, and C/C++ compilers. Refer to the chapter, Using the Compiler for detailed descriptions of the options

ABSOFT COMPILER OPTIONS Option Effect

-c suppresses creation of an executable file — leaves compiled files in object code format

-g generates symbol information for Fx™.

-N9 check for Windows messages more frequently

-O enables a group of basic optimizations which will cause most code to run faster without the expense of application size or memory usage

-o name directs the compiler to produce an executable file called name where name is a Windows file name

FORTRAN 90/95 GENERAL OPTIONS -en causes the compiler to issue a warning whenever the source code contains an extension to the Fortran 90/95 standard.

-w suppresses listing of all compile-time warning messages.

-Zn suppresses messages by message number.

-q suppresses any messages printed to standard output during the compilation process

-v directs the compiler to print status information as the compilation process proceeds

Fortran User Guide 268 Absoft Compiler Option Guide

-N80 causes the compiler to generate code to write the name of the currently executing procedure to standard out.

-zn suppresses messages by message level.

-dq continue compilation if more than 100 errors are encountered.

-ea causes the f90 compiler to abort the compilation process on the first error that it encounters.

-V causes the f90 compiler to display its version number.

-eR directs the compiler to place information in the debugger symbol tables for all structures whether or not they have associated storage

-Tn changes the number of handles used internally by the compiler.

-tn this option increases the default temporary string size to 1024x10n bytes.

-p path specify module search path

FORTRAN 90/95 COMPATIBILITY OPTIONS

-dp causes variables declared in a DOUBLE PRECISION statement and constants specified with the D exponent to be converted to the default real kind.

-ej causes all DO loops to be executed at least once, regardless of the initial value of the iteration count.

-s allocate local variables statically

-xdirective disable compiler directive in the source file.

FORTRAN 90/95 FORMAT OPTIONS -fform sets the form of the source file.

-Wn sets the line length of source statements accepted by the compiler in Fixed-Form source format.

Fortran User Guide Absoft Compiler Option Guide 269

-K directs the compiler to transform certain escape sequences marked with a ‘\’ embedded in character constants.

-YNDFP= disallow the use of a ‘.’ as a structure field separator. The default value is 0 or false.

-TMS7D recognize Microsoft style compiler directives beginning with a ‘$’ in column 1.

FORTRAN 90/95 OTHER OPTIONS -YPEI Pointers are Equivalent to Integers allows a Cray-style pointer to be manipulated as an integer.

FORTRAN 77 GENERAL OPTIONS -w suppresses listing of all compile-time warning messages

-N32 directs the compiler to issue a warning whenever the source code contains an extension to the ANSI FORTRAN 77 standard

!Q19 used when more than one symbolic name is used to reference a variable’s memory location. This can occur when pointers are used, when variables in COMMON are passed as arguments, or when two dummy arguments are the same actual argument.

-q suppresses any messages printed to standard output during the compilation process

-v directs the compiler to print status information as the compilation process proceeds

-N124 causes the compiler to generate code to write the name of the currently executing procedure to standard out.

-C generates code to check that array indexes are within array bounds — file names and source code line numbers will be displayed with all run time error messages

-x replaces any occurrence of X or D in column one with a blank character: allows a restricted form of conditional compilation

Fortran User Guide 270 Absoft Compiler Option Guide

-T used to change the number of handles used internally by the compiler.

-t modifies the default temporary string size to nn bytes from the default of 1024 bytes

FORTRAN 77 CONTROL OPTIONS -D used to define conditional compilation variables from the command line (-D name[=value]) — if value is not present, the variable is assigned the value of 1

FORTRAN 77 COMPATIBILITY OPTIONS -f folds all symbolic names to lower case

-s forces all program storage to be treated as static: see -N1 also

-N3 includes record length information for sequential unformatted files

-N51 if a file is opened as DIRECT access UNFORMATTED, causes the value set with RECL to be interpreted as the number of 32 bit words in a record instead of the number of bytes

-N109 folds all symbolic names to UPPER CASE

-d causes all DO loops to be executed at least once, regardless of the initial value of the iteration count (FORTRAN 66 convention)

-i changes the default storage length of INTEGER and LOGICAL data types to 2 bytes

-N102 directs the compiler to zero extend INTEGER*1 variables to unsigned entities with a range of 0-255 when loaded from memory

-N15 causes the compiler to define SUBROUTINE and FUNCTION names with a trailing underscore

FORTRAN 77 MISCELLANEOUS OPTIONS

Fortran User Guide Absoft Compiler Option Guide 271

-N2 uses only double precision or double complex transcendental intrinsics

-N7 extends the sign of a value returned from BYTE, and WORD intrinsic functions

-N1 causes all variables initialized with DATA statements to be stored as static variables.

-N20 directs the compiler to always evaluate operators of equal precedence from left to right (except for exponential operators)

-N113 changes REAL and COMPLEX data types without explicit length declara-tion to DOUBLE PRECISION and DOUBLE COMPLEX

-K directs the compiler to transform certain escape sequences marked with a ‘\’ embedded in character constants

-N4 suppresses any run-time CASE DEFAULT error messages

-N16 [FMT=] format specifier may be omitted in an I/O statement when [UNIT=] unit specifier is present

-N33 causes structure fields to be “packed” — allocated with no space between them

-N34 automatically align COMMON block variables

FORTRAN 77 FORMAT OPTIONS -8 directs the compiler to accept source code written in Fortran 90/95 Free Source Form

-N112 directs the compiler to accept source code written in IBM VS Free Form

-V directs the compiler to accept VAX Tab-Format source code

-W directs the compiler to accept statements which extend beyond column 72 up to column 132

-N26 force the compiler to consider the byte ordering of all unformatted files to be big-endian by default

-N27 force the compiler to consider the byte ordering of all unformatted files to be little-endian by default

Fortran User Guide 272 Absoft Compiler Option Guide

FORTRAN 77 OTHER OPTIONS

-g generates symbol information for Fx™.

-N111 directs the compiler to place information in the debugger symbol tables for all structures whether or not they have associated storage

-N114 issue a warning diagnostic, rather than an error, for undeclared variables in the presence of an IMPLICIT NONE declaration

-N115 Pad source lines to column 72 (or 132 with –W option)

-N22 don’t mangle COMMON block names with leading “_c”

-N25 export COMMON block names in DLLs

-N110 directs the compiler to accept VAX Tab-Format source code

C/C++ GENERAL OPTIONS -wn suppresses warnings by level.

-wp causes the usage of C++ anachronisms to be treated as errors.

-wabort causes any warning condition to be treated as an error.

-q suppresses any messages printed to standard output.

-v displays the commands it is sending to the compiler and linker.

-N80 causes the compiler to generate code to write the name of the currently executing procedure to standard out.

-ptv causes the compiler to print a message to stderr whenever a template is instantiated.

-H causes an include file tree to be printed to stderr

-T n used to change the number of handles used internally by the compiler.

-maxerr n sets the maximum number of errors that can be emitted before the compiler aborts.

Fortran User Guide Absoft Compiler Option Guide 273

-inline when set to none, prevents the compiler from inlining functions.

-except on enables C++ exception handling.

C/C++ PREPROCESSOR OPTIONS -Dname defines the names and optional values of preprocessor variables.

-Uname undefines the names preprocessor variables.

-P directs the compiler to place the output of the preprocessor in a file which has the same root name as the source file and an extension of .i.

-E directs the compiler to place the output of the preprocessor on stdout.

C/C++ FORMAT OPTIONS -Tp indicates C++ source conforming to the Annotated C++ Reference Manual .

-std allows you to use the namespaces and runtime type information features ANSI C++ in your source code.

-A indicates source which conforms to the ANSI X3.159-1989 standard for the C programming language.

-K used with older style Kernighan and Ritchie C.

Fortran User Guide

275

Appendix B

Linker Error Messages

This appendix lists possible linker and MPW errors that may be encountered when compiling with Absoft Fortran 90/95, FORTRAN 77, C, or C++.

LINKER AND MPW ERROR MESSAGES ### link: Resource not found (OS error -192) ### link: Error: Resource I/O error, # (Error 6) setting resource attributes. This error message is most likely caused by virus detectors such as Vaccine and is often preceded by a “frozen” machine. For Vaccine, a Control Panel option can permit MPW links. See the documentation for the virus detector for permitting linking.

### Unable to swap tool segment

This message means there is no more memory available for compiling or linking. There are a number of steps that may be taken to reduce the amount of memory used or to increase the available memory.

• To increase the memory available to all applications on the Macintosh, remove some of the unnecessary startup documents in the System folder and/or reduce the size of the RAM cache in the Control Panel.

•Use the fsplit utility to break large programs into smaller, more manageable, files. See Chapter 8 for details about fsplit.

• Use the “Use files for temporary storage” option (-F) which causes the compiler to use disk space to store temporary information rather than using memory. This will slow compilation speed and use more disk space, but more memory will be available during compilation.

• Increase the SIZE resource of MPW if you are using MultiFinder. See the section Memory Management in Chapter 6 for details.

• Turn off some compiler optimizations. A few of the optimizations, such as loop unrolling, can consume large amounts of memory. Turning these off or changing their parameters can reduce the memory used by Absoft Fortran 90/95 during compilation.

Fortran User Guide 276 Linker Error Messages

• If using System 6, use the Finder instead of MultiFinder. Since MultiFinder allocates memory to other applications and the system itself, less memory is available when using MPW.

# The read/write permission of only one access path to a file can allow writing (OS error -49)

This error usually occurs when using System 7 or MultiFinder and compiling an application that is already executing. To prevent this, quit the application and recompile.

# Warning: The -ss & -ad linker options are now obsolete.

This error is actually generated by the f77 script and is a reminder that the -ss and -ad options from version 2.1 are now obsolete.

Fortran User Guide 277

Appendix C

ASCII Table

ASCII codes 0 through 31 are control codes that may or may not have meaning on the Macintosh. They are listed for historical reasons and may aid when porting code from other systems. Codes 128 through 255 are extensions to the 7-bit ASCII standard and the symbol displayed depends on the font being used; the symbols shown below are from the Times New Roman font. Most of these characters may be typed with keystrokes; use the Key Caps desk accessory to determine which keystrokes to use. The Dec, Oct, and Hex columns refer to the decimal, octal, and hexadecimal numerical representations.

Character Dec Oct Hex Description Character Dec Oct Hex Description NULL 0 000 00 null 32 040 20 space SOH 1 001 01 start of heading ! 33 041 21 exclamation STX 2 002 02 start of text " 34 042 22 quotation mark ETX 3 003 03 end of text # 35 043 23 number sign ECT 4 004 04 end of trans $ 36 044 24 dollar sign ENQ 5 005 05 enquiry % 37 045 25 percent sign ACK 6 006 06 acknowledge & 38 046 26 ampersand BEL 7 007 07 bell code ' 39 047 27 apostrophe BS 8 010 08 back space ( 40 050 28 opening paren HT 9 011 09 horizontal tab ) 41 051 29 closing paren LF 10 012 0A line feed * 42 052 2A asterisk VT 11 013 0B vertical tab + 43 053 2B plus FF 12 014 0C form feed , 44 054 2C comma CR 13 015 0D carriage return - 45 055 2D minus SO 14 016 0E shift out . 46 056 2E period SI 15 017 0F shift in / 47 057 2F slash DLE 16 020 10 data link escape 0 48 060 30 zero DC1 17 021 11 device control 1 1 49 061 31 one DC2 18 022 12 device control 2 2 50 062 32 two DC3 19 023 13 device control 3 3 51 063 33 three DC4 20 024 14 device control 4 4 52 064 34 four NAK 21 025 15 negative ack 5 53 065 35 five SYN 22 026 16 synch idle 6 54 066 36 six ETB 23 027 17 end of trans blk 7 55 067 37 seven CAN 24 030 18 cancel 8 56 070 38 eight EM 25 031 19 end of medium 9 57 071 39 nine SS 26 032 1A special sequence : 58 072 3A colon ESC 27 033 1B escape ; 59 073 3B semicolon FS 28 034 1C file separator < 60 074 3C less than GS 29 035 1D group separator = 61 075 3D equal RS 30 036 1E record separator > 62 076 3E greater than US 31 037 1F unit separator ? 63 077 3F question mark

Fortran User Guide 278 ASCII Table

Character Dec Oct Hex Description ~ 126 176 7E tilde @ 64 100 40 commercial at 127 177 7F delete A 65 101 41 upper case letter B 66 102 42 upper case letter C 67 103 43 upper case letter D 68 104 44 upper case letter E 69 105 45 upper case letter F 70 106 46 upper case letter G 71 107 47 upper case letter H 72 110 48 upper case letter I 73 111 49 upper case letter J 74 112 4A upper case letter K 75 113 4B upper case letter L 76 114 4C upper case letter M 77 115 4D upper case letter N 78 116 4E upper case letter O 79 117 4F upper case letter P 80 120 50 upper case letter Q 81 121 51 upper case letter R 82 122 52 upper case letter S 83 123 53 upper case letter T 84 124 54 upper case letter U 85 125 55 upper case letter V 86 126 56 upper case letter W 87 127 57 upper case letter X 88 130 58 upper case letter Y 89 131 59 upper case letter Z 90 132 5A upper case letter [ 91 133 5B opening bracket \ 92 134 5C back slash ] 93 135 5D closing bracket ^ 94 136 5E circumflex _ 95 137 5F underscore ` 96 140 60 grave accent a 97 141 61 lower case letter b 98 142 62 lower case letter c 99 143 63 lower case letter d 100 144 64 lower case letter e 101 145 65 lower case letter f 102 146 66 lower case letter g 103 147 67 lower case letter h 104 140 68 lower case letter i 105 151 69 lower case letter j 106 152 6A lower case letter k 107 153 6B lower case letter l 108 154 6C lower case letter m 109 155 6D lower case letter n 110 156 6E lower case letter o 111 157 6F lower case letter p 112 160 70 lower case letter q 113 161 71 lower case letter r 114 162 72 lower case letter s 115 163 73 lower case letter t 116 164 74 lower case letter u 117 165 75 lower case letter v 118 166 76 lower case letter w 119 167 77 lower case letter x 120 170 78 lower case letter y 121 171 79 lower case letter z 122 172 7A lower case letter { 123 173 7B opening brace | 124 174 7C vertical bar } 125 175 7D closing brace

Fortran User Guide ASCII Table 279

Character Dec Oct Hex ¾ 190 276 BE 128 200 80 ¿ 191 277 BF 129 201 81 ‚ 130 202 82 ƒ 131 203 83 „ 132 204 84 … 133 205 85 † 134 206 86 ‡ 135 207 87 ˆ 136 210 88 ‰ 137 211 89 Š 138 212 8A ‹ 139 213 8B Œ 140 214 8C 141 215 8D 142 216 8E 143 217 8F 144 220 90 ‘ 145 221 91 ’ 146 222 92 “ 147 223 93 ” 148 224 94 • 149 225 95 – 150 226 96 — 151 227 97 ˜ 152 230 98 ™ 153 231 99 š 154 232 9A › 155 233 9B œ 156 234 9C 157 235 9D 158 236 9E Ÿ 159 237 9F 160 240 A0 ¡ 161 241 A1 ¢ 162 242 A2 £ 163 243 A3 ¤ 164 244 A4 ¥ 165 245 A5 ¦ 166 246 A6 § 167 247 A7 ¨ 168 250 A8 © 169 251 A9 ª 170 252 AA « 171 253 AB ¬ 172 254 AC - 173 255 AD ® 174 256 AE ¯ 175 257 AF ° 176 260 B0 ± 177 261 B1 ² 178 262 B2 ³ 179 263 B3 ´ 180 264 B4 µ 181 265 B5 ¶ 182 266 B6 · 183 267 B7 ¸ 184 270 B8 ¹ 185 271 B9 º 186 272 BA » 187 273 BB ¼ 188 274 BC ½ 189 275 BD

Fortran User Guide 280 ASCII Table

Character Dec Oct Hex Character Dec Oct Hex À 192 300 C0 à 224 340 E0 Á 193 301 C1 á 225 341 E1 Â 194 302 C2 â 226 342 E2 Ã 195 303 C3 ã 227 343 E3 Ä 196 304 C4 ä 228 344 E4 Å 197 305 C5 å 229 345 E5 Æ 198 306 C6 æ 230 346 E6 Ç 199 307 C7 ç 231 347 E7 È 200 310 C8 è 232 350 E8 É 201 311 C9 é 233 351 E9 Ê 202 312 CA ê 234 352 EA Ë 203 313 CB ë 235 353 EB Ì 204 314 CC ì 236 354 EC Í 205 315 CD í 237 355 ED Î 206 316 CE î 238 356 EE Ï 207 317 CF ï 239 357 EF Ð 208 320 D0 ð 240 360 F0 Ñ 209 321 D1 ñ 241 361 F1 Ò 210 322 D2 ò 242 362 F2 Ó 211 323 D3 ó 243 363 F3 Ô 212 324 D4 ô 244 364 F4 Õ 213 325 D5 õ 245 365 F5 Ö 214 326 D6 ö 246 366 F6 × 215 327 D7 ÷ 247 367 F7 Ø 216 330 D8 ø 248 370 F8 Ù 217 331 D9 ù 249 371 F9 Ú 218 332 DA ú 250 372 FA Û 219 333 DB û 251 373 FB Ü 220 334 DC ü 252 374 FC Ý 221 335 DD ý 253 375 FD Þ 222 336 DE þ 254 376 FE ß 223 337 DF ÿ 255 377 FF

Fortran User Guide 281

Appendix D

Bibliography

FORTRAN 90/95 These books and manuals are useful references for the Fortran 90/95 programming language and the floating point math format used by Absoft Pro Fortran on the Macintosh.

Michael Metcalf and John Reid, FORTRAN 90/95 explained, Oxford University Press (1996)

Walter S. Brainerd, Charles H. Goldberg, and Jeanne C. Adams, Programmer’s Guide to Fortran90, Unicomp, Inc (1994)

Jeanne C. Adams, Walter S. Brainerd, Jeanne T. Martin, and Brian T. Smith, Fortran Top 90, Unicomp, Inc (1994)

James F. Kerrigan, Fortran 90, O’Reilly & Associates, Inc (1993)

American National Standard Programming Language Fortran 90, X3.198-1991, ANSI, 1430 Broadway, New York, N.Y. 10018

COMPUTER, A Proposed Standard for Binary Floating-Point Arithmetic, Draft 8.0 of IEEE Task P754, 10662 Los Vaqueros Circle, Los Alamitos, CA 90720 (1981)

FORTRAN 77 These books and manuals are useful references for the FORTRAN language and the floating point math format used by Absoft Pro Fortran on the Macintosh.

Page, Didday, and Alpert, FORTRAN 77 for Humans, West Publishing Company (1983)

Kruger, Anton, Efficient FORTRAN Programming, John Wiley & Sons, Inc. (1990)

Loren P. Meissner and Elliot I. Organick, FORTRAN 77, Addison-Wesley Publishing Company (1980)

Harry Katzan, Jr., FORTRAN 77, Van Nostrand Reinhold Company (1978)

J.N.P. Hume and R.C. Holt, Programming FORTRAN 77, Reston Publishing Company, Inc. (1979)

Fortran User Guide 282 Bibliography

Harice L. Seeds, FORTRAN IV, John Wiley & Sons (1975)

Jehosua Friedmann, Philip Greenberg, and Alan M. Hoffberg, FORTRAN IV, A Self- Teaching Guide, John Wiley & Sons, Inc. (1975)

James S. Coan, Basic FORTRAN, Hayden Book Company (1980)

American National Standard Programming Language FORTRAN, X3.9-1978, ANSI, 1430 Broadway, New York, N.Y. 10018

COMPUTER, A Proposed Standard for Binary Floating-Point Arithmetic, Draft 8.0 of IEEE Task P754, 10662 Los Vaqueros Circle, Los Alamitos, CA 90720 (1981)

M. Abramowitz and I.E. Stegun, Handbook of Mathematical Functions, U.S. Department of Commerce, National Bureau of Standards (1972)

C AND C++ These books and manuals are useful references for the C and C++ programming languages and the floating point math format used by Absoft Pro Fortran on the Macintosh.

Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Prentice Hall (1988)

Samuel P Harbison and Guy L. Steele Jr., C: A Reference Manual, Prentice Hall (1987)

Bjarne Stroustrup, The C++ Programming Language, Addison-Wesley (1991)

Margaret A. Ellis and Bjarne Stroustrup, The Annotated C++ Reference Manual, Addison-Wesley (1990)

Stanley B. Lippman, C++ Primer, Addison-Wesley (1991)

Ira Pohl, C++ for C Programmers, Benjamin/Cummings (1989)

James T Smith, C++ For Scientists and Engineers, McGraw-Hill (1991)

Scott Meyers, Effective C++, Addison-Wesley (1992)

P.J. Plauger, The Standard C Library, Prentice Hall (1992)

Brian W. Kernighan and P.J. Plauger, Software Tools, Addison-Wesley Publishing Company (1976)

Brian W. Kernighan and P.J. Plauger, The Elements of Programming Style, McGraw-Hill Book Company (1978)

Fortran User Guide Bibliography 283

American National Standard Programming Language C, X3.159-1989, ANSI, 1430 Broadway, New York, N.Y. 10018

COMPUTER, A Proposed Standard for Binary Floating-Point Arithmetic, Draft 8.0 of IEEE Task P754, 10662 Los Vaqueros Circle, Los Alamitos, CA 90720 (1981)

MACINTOSH PROGRAMMING These books are suggested reading for learning how to program the Macintosh toolbox. In addition, Apple Computer Inc. maintains extensive technical resources at their web site in the “developer” area:

http://www.apple.com

Apple Computer Inc., Inside Macintosh, volumes I-VI, Addison-Wesley Publishing Company (1985-1991)

Apple Computer Inc., Programmer’s Introduction to the Macintosh, Addison-Wesley Publishing Company (1989)

Apple Computer Inc., Inside Macintosh: RISC System Software, Addison-Wesley Publishing Company (1994).

Apple Computer Inc., Inside Macintosh: RISC Numerics, Addison-Wesley Publishing Company (1994).

Apple Computer Inc., Human Interface Guidelines, Addison-Wesley Publishing Company (1987).

Apple Computer Inc., Macintosh Programmer’s Workshop, Apple Programmers and Developers Association (1985-1991

Apple Computer Inc., Macintosh Technical Notes, Apple Programmers and Developers Association (1985-1991).

Fortran User Guide

285

Appendix E

Technical Support

The Absoft Technical Support Group will provide technical assistance to all registered users of current products. They will not answer general questions about operating systems, operating system interfaces, graphical user interfaces, or teach programming. For further help on these subjects, please consult this manual and any of the books and manuals listed in the bibliography.

Before contacting Technical Support, please study this manual and the language reference manuals to be sure your problem is not covered here. Specifically, refer to the chapter Using The Compilers in this manual. To help Technical Support provide a quick and accurate solution to your problem, please include the following information in any correspondence or have it available when calling.

Product Information:

Name of product Version number Serial number Version number of the operating system

System Configuration:

Hardware configuration (hard drive, etc.). System software release (i.e. 4.0, 3.5, etc). Any software or hardware modifications to your system.

Problem Description:

What happens? When does it occur? Provide a small (20 line) step-by-step example if possible.

Fortran User Guide 286 Technical Support

Contacting Technical Support:

Address: Absoft Corporation Attn: Technical Support 2781 Bond Street Rochester Hills, MI 48309 telephone: (248) 853-0095 9am - 3pm EST FAX (248) 853-0108 24 Hours email [email protected] 24 Hours World Wide Web http://www.absoft.com

Fortran User Guide 287

Appendix F

Differences Between Pro Fortran V6.2 and V7.0

This appendix summarizes changes form Absoft Pro Fortran V6.2 to V7.0. Where applicable, sections of the manuals are listed for reference.

CARBON LIBRARY

All compilers now support code production compatible with the Macintosh Carbon Library. The Carbon Library allows you to produce programs that are compatible with both the classic Macintosh environment and the native Macintosh OS X environment. See the chapters Using the Compilers and The Macintosh Runtime Window Environment for details.

SHARED LIBRARIES

The creation of shared libraries is not supported for MRWE applications or any library that uses Fortran I/O.

FORTRAN 90

Promote to Double Precision. The Fortran 90 compiler now supports automatic promotion of 32-bit REAL(KIND=4) and COMPLEX(KIND=4) to equivalent 64-bit data types (KIND=8). See the chapter Using the Compilers for details.

Promote to 64-bit Integer. The Fortran 90 compiler now supports automatic promotion of 32-bit INTEGER(KIND=4) to equivalent 64-bit data types (KIND=8). See the chapter Using the Compilers for details.

Debugging Options. The Fortran 90 compiler now supports a number of options for checking that array indices are with the bounds of an array, that character substring expressions do not specify a range outside of the variable, array conformance, and POINTER references are not null. See the chapter Using the Compilers for details.

FORTRAN 77 Promote to 64-bit Integer. The FORTRAN 77 compiler now supports automatic promotion of 32-bit INTEGER*4 to equivalent 64-bit data types INTEGER*8. See the chapter Using the Compilers for details.

Fortran User Guide 288 Differences Between Pro Fortran V6.2 and V7.0

Fortran User Guide 289

Appendix G

Interfacing with MetroWerks CodeWarrior

This appendix describes how to interface object modules produced by the Absoft Pro Fortran compilers for PowerPC with MetroWerks projects. The Absoft compilers produce code that may be used in MetroWerks Codewarrior projects. However, because the Codewarrior environment does not produce object files that are compatible with the Absoft linker, the final program must be created inside Codewarrior. This appendix provides details on importing Pro Fortran object files into a Codewarrior project. For information on inter-language calling conventions, refer to the chapter Macintosh Programming.

PRODUCING THE FORTRAN OBJECT CODE Before you can import Pro Fortran code into a Codewarrior project, you must first compile it into object format. This step is performed inside the MPW environment using the Absoft Pro Fortran compiler. If you have only a single routine, you can simply select the No executable (object file only) option in addition to any other options your code may require. However, if you are using many routines or if your FORTRAN code makes use of COMMON blocks, you will need to create a static library using the Absoft linker. For information on creating libraries, refer to the chapter Building Programs, earlier in this manual.

ADDING FORTRAN OBJECT FILES TO A CODEWARRIOR PROJECTS

After starting Codewarrior and opening your project, use the Add… item, located in the Project menu, to add your routine or library to your project. If your FORTRAN code makes use of INTRINSIC functions or I/O statements, you will also need to add the FORTRAN library, libfmath.o and libfio.o, to your project as well. Finally, rebuild your project using the Make item that is also located in the Project menu.

DEBUGGING FORTRAN WITH THE METROWERKS DEBUGGER With the release of Codewarrior 8, MetroWerks has added some support for debugging Absoft Pro Fortran code with the MetroWerks debugger. You can view source code, set breakpoints, and examine the values of simple variables. You cannot examine multi- dimensional arrays, variables within COMMON blocks, or variables declared with the RECORD or POINTER statement.

Fortran User Guide

291

Appendix H

Language Systems Fortran Extensions

This appendix describes the implementation of Language Systems Fortran extensions supported by the Absoft FORTRAN 77 Compiler.

STRING

STRING is a type statement and is used to declare a string entity compatible with Pascal strings. The first data byte of a STRING is set to the logical length of the string, limiting the length of a character entity declared in this manner to 255 bytes. With the exception of internal files and substring expressions, a STRING can be used anywhere a CHARACTER argument can be used.

POINTER This is a declaration statement for declaring variables that will contain the address of other variables. The syntax is:

POINTER /type/ v [, v] ...

where: type is a type or structure name. v is a variable name.

A POINTER may be used in an assignment statement or in an integer expression to manipulate the address it contains. It is dereferenced (the value of what it points to is extracted) by appending the operator, ^, to the name.

LEAVE

This statement has the same meaning as the EXIT statement (See Control Statements in the FORTRAN 77 Reference Manual) and provides a convenient means for abnormal termination of a DO loop. The LEAVE and EXIT statements cause control of execution to be transferred to the statement following the terminal statement of a DO loop or block DO.

GLOBAL

The syntax of this statement is similar to the SAVE statement (see Specification and DATA Statements in the FORTRAN 77 Reference Manual). The variables specified with a GLOBAL statement are made externally visible. It can be used in conjunction with GLOBAL DEFINE to create global variables for the whole file.

Fortran User Guide 292 Language Systems Fortran Extensions

CGLOBAL

The syntax of this statement is similar to the SAVE statement (see Specification and DATA Statements in the FORTRAN 77 Reference Manual). The variables specified with a CGLOBAL statement are not affected by case folding and are made externally visible. It can be used in conjunction with GLOBAL DEFINE to create global variables for the whole file.

PGLOBAL

The syntax of this statement is similar to the SAVE statement (see Specification and DATA Statements in the FORTRAN 77 Reference Manual). The variables specified with a PGLOBAL statement are folded to upper case and made externally visible. It can be used in conjunction with GLOBAL DEFINE to create global variables for the whole file.

CEXTERNAL

The syntax of this statement is similar to the EXTERNAL statement (see Specification and DATA Statements in the FORTRAN 77 Reference Manual). The functions specified with a CEXTERNAL statement pass all of their arguments by value as the default. An argument can be passed by reference if the %REF intrinsic function is used.

PEXTERNAL

The syntax of this statement is similar to the EXTERNAL statement (see Specification and DATA Statements in the FORTRAN 77 Reference Manual). The functions specified with a PEXTERNAL statement pass all of their arguments by value as the default. An argument can be passed by reference if the %REF intrinsic function is used. Note that this statement has the same effect as the Absoft PASCAL EXTERNAL declaration.

INT1, INT2, AND INT4

INT1, INT2, and INT4 are type conversion intrinsic functions that convert their arguments to 1-, 2-, and 4-byte integers respectively.

JSIZEOF This function returns an integer that represents the size of its argument in bytes. It is identical to the SIZEOF function (see Programs, Subroutines, and Functions in the FORTRAN 77 Reference Manual).

%VAL, %REF, AND %DESCR

When appearing in the formal argument list of a FUNCTION or SUBROUTINE declaration statement, these statements use the syntax of a function reference, but have the affect of declaring the passing method of the argument. %DESCR has no effect (but will generate a

Fortran User Guide Language Systems Fortran Extensions 293

warning diagnostic), %REF is the default, and %VAL is the same as using the VALUE declaration statement (see Specification and DATA Statements in the FORTRAN 77 Reference Manual). The % is not optional in this usage.

LANGUAGE SYSTEMS INCLUDE FILES There are some syntactical difficulties in several of the Language Systems API include files that are ignored by the Language Systems Fortran compiler. These are detected by the Absoft FORTRAN 77 compiler which will issue a diagnostic when they are encountered.

Fortran User Guide

Index

≈ character ...... 41 Carbon...... 4 ? character...... 41 carriage control, printing...... 206 ≥ symbol ...... 40 carriage returns 132 column source code...... 87, 107 adding ...... 125 386, porting from ...... 127 changing from line feeds...... 126 72 Column Window command ...... 133 Cascade command...... 254 A/UX environment...... 128 CASE DEFAULT ...... 109 Absoft address...... 286 Catenate command ...... 52 Absoft compilers...... 289 Change command...... 250 Absoft Fortran 77 compiler changing linefeed character...... 126 previous version...... 289 Character Map application ...... 277 access path error...... 276 check array boundaries...... 98 Actions menu ...... 251 CheckHEXA tool ...... 131 Add Path command...... 233, 242 Choose command ...... 51 Adding Menus...... 167 Chooser desk accessory...... 23 Address command...... 249 Classes command ...... 256 aggregate...... 237 Clear All Breakpoints command ...... 248 Alert command ...... 64 Clear command ...... 243, 264 Alert dialog box ...... 183 Clear menu command...... 24, 164 Alias command ...... 61 Clipboard...... 17, 24, 163 Align menu command...... 25 in a separate window...... 24 alignment Close box...... 185, 186 automatically align COMMON ...... 109 Close command...... 242, 263 Alphabetical menu command...... 30 Close menu command ...... 22 appcbe tool...... 136 Code command...... 257 Apple events ...... 201 Code For...... 250 Apple Events...... 172 code window ...... 257 class ...... 173 colon, in path names...... 131 ID 173 color Quickdraw example ...... 206 target...... 173 Command-Enter ...... 162 Apple menu...... 23 Command-key equivalent...... 19 application icon...... 153, 222 Commando command...... 62 arguments, tool...... 206 commando interface ...... 62 array Commando interface ...... 12, 38, 72 boundary checking...... 93, 98 Command-Period arrays ...... 237 termination...... 83, 101 Ascending command...... 266 Command-Period ASCII table ...... 277 checking...... 161 Assembly command...... 254 key ...... 3 assembly language ...... 241, 247 Command-Return...... 162 interfacing with FORTRAN ...... 220 COMMON blocks from C...... 212 balloon help ...... 155, 223 COMMON, aligning data...... 109 basic optimizations ...... 86, 102 compatibility, introduction...... 3 Beep command ...... 65 compiler directives ...... 94 BLOCK=-1 specifier...... 105 FIXED directive...... 95 BNDL resource...... 154, 223 FREE directive...... 95 branch instructions...... 83, 98 NAME directive...... 95 breakpoint condition ...... 236, 255 STACK directive ...... 96 breakpoint control dialog ...... 235, 256 compiler options...... 267 breakpoints...... 234 -!N61, use temporary files ...... 114 Breakpoints command ...... 255 -8, Fortran 90 ...... 107 Browse menu command...... 29 -A, ANSI C ...... 113 By Calls command...... 265 -A, suppress alignment warnings ...... 97 By Name command...... 265 -align, use 68k alignment...... 116 By Time command...... 265 -appleext off, suppress Apple extensions...... 116 By Time/Call command...... 265 -C, check boundaries...... 98 BYTE sign extension ...... 109 -c, object files...... 101 C -char, make chars unsigned...... 117 function results ...... 210 -D, define compiler variable ...... 101 interfacing with FORTRAN(see interfacing -d, define preprocessor variable ...... 118 FORTRAN and C) -d, one trip DO loops...... 106

Fortran User Guide Index

-E, preprocess to stdout ...... 119 -N7, sign extend...... 109 -ea , stop on error...... 84 -N80, procedure trace ...... 85 -ej, one trip DO loops...... 88 -N9, Command-Period...... 83, 101 -en, non-standard usage...... 84 -O, basic optimizations ...... 86, 102 -enum, use int enums...... 116 -o, executable name ...... 78, 101 -ep, demote Double Precision...... 87 -O, optimize ...... 79 -eq, allow greater than 100 errors...... 84 -p, MODULE path ...... 90 -eR, default recursion ...... 84 -P, preprocess to file ...... 119 -except, exception handling...... 114 -p, profiling...... 98, 114 -f, case fold...... 105, 121 -profile, profiling ...... 85 -f, fixed source form...... 87 -ptv, verbose templates ...... 119 -f, freed source form...... 87 -q, quiet...... 119 -F, temporary files ...... 84, 101, 275 -q, quiet...... 100 -g, debug...... 79 -Q51, no fma instructions ...... 108 -g, Fx debugging...... 98, 121 -Rb, check array conformance ...... 93 -gmin, Fx debugging ...... 98 -Rb, check boundaries...... 93 -H, include tree to stderr...... 119 -Rp, check pointers ...... 93 -H, max lines to unroll...... 103 -Rs, check substrings ...... 93 -h, unroll count ...... 103 -s, static storage ...... 87, 105, 121, 130 -I, INCLUDE path...... 74 -std, draft std C++...... 113 -i, integer sizes...... 88, 106 -T, max internal handle...... 89, 99 -I, MODULE file...... 90 -t, temporary strings...... 89, 110 -init, set initialization prefix ...... 117 -term, set termination prefix ...... 117 -inline none, no inlines ...... 114 -Tp, ARM C++ ...... 112 -K, escape sequences...... 92, 109 -U, loop unrolling ...... 103 -K, K&R C ...... 113 -u, undefine preprocessor variable...... 118 -m, delayed stores...... 99 -v , show progress ...... 83, 100 -M, extern globals...... 106 -V , show version...... 84 -maxerr, max errors ...... 115 -V, VAX Tab-Format ...... 107 -N1, static storage...... 105, 109 -v, verbose ...... 119 -N102, zero extend INTEGER*1 ...... 106 -W, line length ...... 87 -N109, case fold ...... 105 -w, suppress compiler warnings...... 83, 97 -N11, 32 bit branches ...... 83, 98 -W, wide format...... 107 -N110, no Common mangling ...... 111 -w1, suppress template warnings ...... 115 -N111, debugging structures...... 99 -w16, suppress warnings...... 115 -N112, IBM VS Free-Form ...... 107 -w31, suppress all warnings...... 115 -N113, floating point sizes ...... 87, 109 -w8, suppress anachronism warnings...... 115 -N114, warnings for undeclared variables...... 111 -w8, suppress informational warnings ...... 115 -N115, pad source lines ...... 111 -wabort, treat all warnings as errors...... 115 -N124, procedure trace ...... 98, 114 -wp, treat anachronisms as errors...... 115 -N15, append underscore...... 110 -x , disable compiler directive...... 88 -N16, UNIT specifier...... 109 -x, conditional compilation ...... 99 -N17,Pascal function ...... 110 -YCOM_NAMES, COMMON block case ...... 92 -N18, function decomposition ...... 103 -YCOM_PFX, COMMON block prefix ...... 92 -N18, use long branches ...... 113 -YCOM_SFX, COMMON block suffix...... 92 -N2, double precision ...... 108 -YDEALLOC, cache control ...... 94 -N20, left-to-right ...... 108 -YEXT_NAMES, external names...... 93 -N21, Pascal keyword...... 110 -YEXT_SFX, external symbol suffix ...... 93 -N22, set Common name...... 107 -YNDFP, type elements...... 92 -N26, set big-endian ...... 107 -z, suppress messages ...... 85 -N27, set little-endian...... 107 -Z, suppress warning number...... 85 -N3, record lengths...... 105 Compiler Options...... 228, 260, 265 -N32, non-ANSI ...... 106 compiler version...... 84 -N34, align COMMON ...... 109 compiling Fortran source...... 9 -N4, CASE DEFAULT ...... 109 complex data types -N5, treat DATA as constants...... 102 equivalent declarations in C...... 207 -N51, 32 bit RECL ...... 105 in Pascal...... 213 -N57, align structure fields to 2-byte boundaries; conditional compilation...... 99 ...... 110, 111 conditional compilation variables ...... 101 -N58, align structure fields to 4-byte boundaries; Configure command...... 253, 262 ...... 111 Confirm command ...... 64 -N59, align structure fields to 8-byte boundaries; constant propagation ...... 102 ...... 111 continuation lines...... 122

Fortran User Guide Language Systems Fortran Extensions 3

Continue command ...... 246 Entire Word...... 26 Control menu ...... 246 error messages...... 80, 275 conventions used in the manual ...... 3 errors ...... 84 Copy command...... 243, 264 at runtime ...... 123 Copy menu command ...... 24, 163 escape sequences in strings ...... 109 could not launch error ...... 16 event loop...... 166 Create Build Commands… ...... 144, 145 example programs ...... 206 creating a new text file...... 21 DateTime.f...... 206 current folder ...... 79, 189 Hello.f90 ...... 13 cursor example...... 206 MRWE source code ...... 206 Cut command...... 243, 264 plotting ...... 206 Cut menu command ...... 24, 163 printing ...... 206 data initialization to zero...... 105 exceptions DATA treated as constants ...... 102 divide by zero...... 134 Date command ...... 59 operand error...... 134 date example...... 206 overflow...... 134 DATE subroutine...... 122 executable name, specifying ...... 78, 101 debugging ...... 98, 99, 111, 225 extensions array bounds checking...... 98 key Microsoft FORTRAN...... 124 conditional compilation ...... 99 key Sun FORTRAN ones...... 126 DebugServices for PowerPC...... 231 key VAX FORTRAN ones ...... 121 delayed stores...... 99 key VS FORTRAN ones...... 123 Delete command ...... 48 extensions to FORTRAN 77 ...... 3 deleting Worksheet text ...... 80 f77 tool ...... 136 DeRez tool ...... 152 f77 tool options Descending command...... 266 -appl, application with MRWE ...... 138 Dev -link, options for linker ...... 138 Null ...... 40 -plainappl, generate application ...... 137 StdErr...... 40 -tool, generate a tool ...... 138 diagnostic output...... 40 f77fe tool...... 136 Differences...... 287 f77init.o startup ...... 195 differences, between Absoft Fortran 77 versions....289 F90Includes folder...... 192 Directory command ...... 60, 79 FExamples folder ...... 206 Directory menu ...... 30, 79 file Directory menu or by entering the following line in markers...... 29 the Worksheet:...... 189 names ...... 131 display compiler alignment warning messages...... 97 File Display Selection menu command...... 27 command...... 68 distribution issues ...... 128 creator ...... 187 divide by zero exceptions...... 134 menu ...... 21 DO loops type ...... 187 one trip...... 106 FILE ...... 132 DO Loops...... 88 File menu...... 241, 263 documentation conventions...... 3 Files command ...... 47 double colon...... 132 FIncludes folder ...... 192 double precision Find Again command ...... 251 functions ...... 108 Find command...... 251 Down command...... 247 Find line numbers...... 25 dynamic memory allocation...... 131 Find menu...... 25 Edit menu...... 23, 242, 264 Find menu command...... 25 Editing commands Find Same menu command ...... 27 Edit menu...... 23 Find Selection menu command ...... 27 File menu...... 21 Finder Find menu...... 25 icons...... 153, 222 Mark menu...... 29 Finder information editing files ...... 9 example...... 206 eject command ...... 40 FIXED directive ...... 95 Eject command ...... 49 floating point enabling the exception ...... 134 unit ...... 133 Enabling/Disabling Menu Items ...... 170 floating point unit end-of-file character...... 162 exception handling...... 134 Enter key...... 20 rounding direction...... 134 Enter key...... 2 Flush command ...... 49

Fortran User Guide Index fold to lower case...... 105 Hide Calls command...... 265 font name...... 43 Hide Graph command ...... 265 font size ...... 43 Hide Time command...... 264 Force Quit ...... 161 Hide Time/Call command...... 265 FORM='BINARY' specifier ...... 125 Hide/Show Toolbar command ...... 254 Format command...... 133 hierarchical folder structure ...... 132 Format menu command ...... 24 Home command ...... 247 Fortran 77 IBM RS/6000, porting from...... 127 introduction ...... 1 icon, application...... 153, 222 options...... 96 IDATE subroutine...... 122 FORTRAN 77 extensions3, 99, 105, 106, 107, 109, IEEE floating point math ...... 133 110 IMPLICIT NONE statement ...... 195 COMPLEX size...... 109 IMSL library ...... 76 conditional compilation...... 99 INCLUDE files escape sequences ...... 109 for resources...... 153, 222 Fortran 90 Free Source Form...... 107 toolbox dependencies...... 192 IBM VS Free Form...... 107 INCLUDE path ...... 74 INTEGER size...... 106 include tree to stderr...... 119 LOGICAL size ...... 106 Info command ...... 263 lower case...... 105 initialization routines...... 195 one trip DO...... 106 input from keyboard...... 162 REAL size ...... 109 Inside Macintosh...... 190 REPEAT INTEGER, 2-byte default ...... 106 function ...... 110 INTEGER, 8-byte default ...... 106 upper case...... 105 Intel 386, porting from...... 127 VAX Tab-Format ...... 107 interface files...... 192 wide source format ...... 107 interfacing FORTRAN and C FORTRAN 77 interface files...... 192 calling FORTRAN math routines ...... 211, 219 Fortran 90 compatible type declarations ...... 207 options...... 82 function call to C from FORTRAN ...... 210 Fortran 90 Fixed Source Form...... 87 function call to FORTRAN from C ...... 211 Fortran 90 Free Source Form...... 87, 107 function results...... 210 Fortran 90 interface files...... 192 LOC function...... 210 FORTRAN math routines passing an array ...... 210 calling from C...... 211, 219 passing pointers ...... 208 FPU Registers command ...... 259 passing strings...... 211 FREE directive ...... 95 passing values ...... 208 FREF resource ...... 154, 223 reference parameters...... 208 frequent Command-Period checks...... 83, 101 passing to C ...... 209 fsplit utility ...... 275 passing to FORTRAN ...... 208 Fsplit utility tool ...... 138 VAL function...... 209 FTNCHEK utility tool ...... 139 value parameters ...... 209 full path name ...... 131 interfacing FORTRAN and Pascal function call to FORTRAN from Pascal ...... 218 call to C from FORTRAN ...... 210 call to Pascal from FORTRAN ...... 218 call to FORTRAN from C ...... 211 compatible type declarations ...... 213 call to FORTRAN from Pascal...... 218 function results...... 218 call to Pascal from FORTRAN...... 218 passing strings...... 219 decomposition ...... 103 passing values ...... 216 Fx 98, 111 reference parameters...... 216 General Registers command ...... 258 passing to FORTRAN ...... 216 Get Info command ...... 129 passing to Pascal...... 216 GetFileName command ...... 64 VAL function...... 217 GLOBAL...... 106 value parameters ...... 217 graying of text...... 3 intermediate files...... 84, 101 handle ...... 199 intrinsic functions example ...... 206 LOC ...... 210 Hello.f90 file...... 13 math ...... 211, 219 Help command...... 58 VAL...... 209, 217 help for MPW commands...... 11 italicized text, defined...... 3 HEXA resource...... 158 keyboard input ...... 162 in MPW ...... 131 Kill command...... 246 hexa tool ...... 158 Language Systems Fortran...... 127, 291

Fortran User Guide Language Systems Fortran Extensions 5

LAPACK library...... 77 MoveWindow command ...... 69 large applications ...... 156, 224 MPW Launching OTHER APPLICATIONS...... 171 documents ...... 9 left-to-right operator evaluation...... 108 Shell ...... 2 license for redistribution ...... 128 Shell icon ...... 9 Line command ...... 67, 249 Worksheet ...... 33 linefeed character, changing ...... 126 MPW commands...... 46 linefeed character, removing...... 125 MPW stack size...... 158 Linker Options ...... 230, 261 MRWE ...... 83, 101 Literal ...... 26 adding an icon...... 154, 223 Lnk tool...... 150 and the toolbox...... 196 LOC, intrinsic function ...... 210 basics...... 16 local variables ...... 158 customization ...... 164 Locals command ...... 249 Event Loop...... 166 LONG sign extension ...... 109 programming...... 164 loop unrolling...... 103 source code ...... 206 MacFortran ...... 128 MRWE.o file...... 159 MacFortran II...... 128 mrwe_AddMenu ...... 167 MacFortran/020 ...... 128 mrwe_DoMenu ...... 169 MacFortran/AUX...... 128 MS-DOS files, translating ...... 125 Macintosh Programmer’s Workshop (MPW) ...... 2 MS-DOS, porting from...... 124 Macintosh toolbox ...... 4 Multiple Windows...... 182 Macintosh User Interface,...... 9 munch...... 117 make chars unsigned...... 117 -N9 ...... 161 makefile tutorial...... 149 NAME directive ...... 95 Mark command ...... 62 New Assembly command...... 241 Mark menu...... 29 New menu command...... 21 Mark menu command ...... 29 New Source command...... 241 markers, text ...... 29 NewFolder command ...... 47 master pointer ...... 199 Next command ...... 249 math routines Next Error menu command ...... 28 FORTRAN ...... 211, 219 NeXT, porting from...... 126 max errors ...... 115 NLS message catalogs...... 43 Memory command...... 257 no inlines...... 114 memory management...... 129 non ANSI warnings...... 106 Memory Management...... 158 null device...... 40 menu object files, generating ...... 101 adding ...... 167 off-screen bitmap example ...... 206 checkmarks...... 170 On command ...... 253, 262 deleting ...... 169 one trip DO...... 106 deleting an item ...... 169 open additional windows...... 182 is blank error...... 130 Open command ...... 241, 263 item, enabling and disabling...... 170 Open menu command...... 22 menus Open Selection menu command...... 22 Apple ...... 23 OPEN statement ...... 132 Edit ...... 23 Open Workspace command...... 241 File...... 21 operand error exceptions ...... 134 Find...... 25 operator evaluation...... 108 Mark ...... 29 optimization...... 85, 102 Tools...... 72 basic optimization ...... 86, 102 Window ...... 30 constant propagation ...... 102 Menus function decomposition...... 103 Directory...... 30 optimizations metacommands, Microsoft FORTRAN ...... 125 loop unrolling...... 103 Microsoft FORTRAN options...... 267 metacommands ...... 125 Options porting from...... 124 Compilers...... 228, 260 Mixed Mode Manager...... 197 Linker...... 230, 261 modifier keys ...... 3 options, manual convention...... 3 MODULE ...... 90 other porting issues...... 128 MODULE file...... 90 output redirection ...... 40 MODULE path ...... 90 overflow exceptions ...... 134 Move command ...... 49 Page Setup command ...... 263

Fortran User Guide Index page setup dialog ...... 163 Replace Same menu command ...... 28 Page Setup menu command...... 23 Request command...... 63 partial path name ...... 131 Required Apple Events ...... 174 Pascal resource compiler...... 136, 221 function results ...... 218 resource description file ...... 136, 151, 221 interfacing with FORTRAN(see interfacing resource editor...... 136, 221 FORTRAN and Pascal) resource include files ...... 153, 222 Pascal function...... 110 resources ...... 221 passing arguments to toolbox ...... 193 Restart command...... 246 Paste command ...... 243, 264 Return command...... 246 Paste menu command ...... 24, 164 Return key...... 2, 20 path names...... 131 Revert to Saved menu command...... 23 pause after the program ends ...... 185 Rez include files...... 43 PenState structure ...... 197 Rez tool...... 151 plotting example ...... 206 RIncludes folder...... 153, 222 pointer, passing to toolbox...... 197 road maps...... 4 Pointers...... 237, 251, 252 routing command output ...... 39 porting code ...... 121 RS/6000, porting from ...... 127 doesn’t run correctly;...... 123 Run To command...... 247 from IBM RS/6000...... 127 runtime error messages ...... 275 from Intel 386...... 127 runtime error messages ...... 123 from Microsoft FORTRAN...... 124 Runtime preferences ...... 184 from MS-DOS ...... 124 Save a Copy menu command...... 23 from NeXT ...... 126 Save As menu command...... 23 from SCO Unix ...... 127 Save menu command ...... 22 from Sparc...... 126 SAVE statements ...... 158 from Sun FORTRAN ...... 126 Save Window Positions command...... 242 from VAX FORTRAN ...... 121 Save Workspace command ...... 242 from VS FORTRAN...... 123 saveOnClose ...... 185 PPCTraceEnabler...... 231 saving Worksheet text...... 80 preconnected units ...... 160 SCO Unix, porting from...... 127 Preferences command...... 243 scope ...... 239, 248 preprocess to file...... 119 script files...... 43 preprocess to stdout ...... 119 scriptable application ...... 181 preprocessor variables ...... 118 Search command...... 52 Prev command ...... 249 SECNDS subroutine...... 122 Previous menu command...... 28 Select All command...... 243 Print ...... 237, 251, 252 Select All command...... 80 Print * ...... 251, 252 Select All menu command ...... 24 Print As command ...... 252, 253 Selection Expression...... 26 Print command...... 67, 263 Sending Apple Events ...... 175 Print menu command...... 23 Set Breakpoint On...... 253 printing example ...... 206 Set command...... 60 Profile menu ...... 253 Set current directory...... 31, 79 profiling ...... 85, 98, 114, 226, 228, 253, 262 Set Directory menu command...... 31, 79 profmt ...... 254 set initialization prefix ...... 117 Profmt...... 262 set termination prefix ...... 117 qualifiers, VAX FORTRAN ...... 122 SetCurs.f example ...... 200 Quickdraw Globals ...... 201 SetDirectory command ...... 61, 79 Quickdraw.inc file ...... 192 SetFile command...... 51 quiet...... 119 SetPrefs Quit command ...... 65, 242, 264 Tool...... 184 Quit menu command...... 23, 163 SetPrefs Tool...... 184 RAN function ...... 122 setting tab size...... 133 random numbers...... 206 setting window to 72 columns...... 133 Receiving Apple Events ...... 176 shared data ...... 106 RECL shared libraries...... 287 for 32-bit words...... 105 Shift menu commands...... 25 RECORD statement...... 196, 197 Show Clipboard menu command ...... 24 redirection of output ...... 40 show compiler progress...... 83, 100 removing linefeed character...... 125 Show Directory menu command...... 31 Rename command ...... 50 Show Program Counter command ...... 248 Replace menu command...... 28 Shutdown command...... 65

Fortran User Guide Language Systems Fortran Extensions 7 single stepping ...... 234 timer interval ...... 187 SIZE resource ...... 155, 186, 224 tool arguments example ...... 206 setting ...... 129 toolbox example programs ...... 206 SIZE(-1) resource ...... 230 Tools menu...... 72 SizeWindow command ...... 69 tracing...... 85, 98, 114 skip count...... 236, 255 treat all warnings as errors...... 115 Sort menu...... 265 treat anachronisms as errors ...... 115 source line length...... 87 tutorial Sparc, Absoft compiler for...... 126 books for beginners...... 282 Sparc, porting from ...... 126 compiling with Commando...... 13 spooling example ...... 206 Types command ...... 250 square brackets, defined...... 3 Unable to swap tool segment...... 275 Stack command...... 259 underlined text, defined...... 3 STACK directive ...... 96 underscores in routine names ...... 110 Stack window...... 240 Undo command ...... 243, 264 Stack Windows menu command...... 30 Undo menu command ...... 23, 163 standard file dialog...... 132 UNIT specifier ...... 109 standard file example ...... 206 Universal Procedure Pointers ...... 197, 198 standard output...... 40 Unix compatibility library...... 76 suppressing ...... 100 Unix files, translating ...... 126 startup documents ...... 275 Unmark command ...... 62 startup initialization ...... 195 Unmark menu command ...... 29 static storage ...... 87, 105, 158 UnSet command ...... 60 Statics command ...... 249, 250 Up command ...... 248 Step Into command ...... 247 use 68k alignment...... 116 Step Over command...... 247 use int enums...... 116 Stop command ...... 246 use long branches ...... 113 stop program execution...... 161 use temporary files ...... 114 string length ...... 89, 110 using compiled applications ...... 9 strings using the toolbox ...... 190 passing FORTRAN to C...... 211 Vaccine...... 275 passing FORTRAN to Pascal ...... 219 VAL function ...... 193 STRUCTURE fields, aligning ...... 110, 111 VALUE statement...... 193, 209, 217 STRUCTURE statement...... 196 variables ...... 236, 240 Sun FORTRAN, porting from...... 126 variables, environment ...... 42 support ...... 285 VAX FORTRAN suppress all warning messages...... 115 porting from ...... 121 suppress anachronism warning messages...... 115 qualifiers ...... 122 suppress Apple extensions ...... 116 VAX Tab-Format source...... 107 suppress delayed stores...... 99 VAX/VMS compatibility library...... 76 suppress informational warning messages ...... 115 verbose ...... 119 suppress list of compiler warning messages...... 83, 97 verbose templates ...... 119 suppress template warning messages ...... 115 View As command ...... 250 suppress warning messages...... 115 View current directory ...... 31 switching between applications ...... 161 View menu ...... 248 Symbols command...... 259 virus detectors ...... 275 Symbols window...... 236, 249, 250, 252, 259 Volumes command...... 50 System 6 notes ...... 276 VS FORTRAN, porting from...... 123 System 7...... 161 warn of non-ANSI usage...... 106 system errors...... 158 warning messages...... 80 tab character...... 133 Watch *, ...... 252 tab size ...... 25 Watch All command...... 252 TABSIZE variable ...... 138 Watch Locals command ...... 253 Target command ...... 67 WhereIs command...... 49 technical support...... 285 whetstone benchmark...... 206 Text characteristics ...... 186 wide source format...... 107 text markers ...... 29 Window characteristics ...... 185 text, not displayed...... 130 Window menu ...... 30 Tile command ...... 254 Window name...... 185 Tile Windows menu command ...... 30 Windows command...... 68 TileWindows command ...... 68 Windows menu...... 254 time example...... 206 WORD sign extension...... 109 TIME subroutine...... 122 Worksheet, deleting text...... 80

Fortran User Guide Index

Y2K bug ...... 7 Σ symbol ...... 40 ZoomWindows command...... 68

Fortran User Guide