Upload
dangtu
View
251
Download
1
Embed Size (px)
Citation preview
Power Macintosh™Fortran & C/C++ User Guide
Pro Fortran
Pro Fortran
Power Macintosh™Fortran & C/C++ User Guide
2781 Bond StreetRochester Hills, MI 48309U.S.A.Tel (248) 853-0095Fax (248) [email protected]
All rights reserved. No part of this publication may be reproduced or used in any form by any means, without theprior written permission of Absoft Corporation.
THE INFORMATION CONTAINED IN THIS PUBLICATION IS BELIEVED TO BE ACCURATEAND RELIABLE. HOWEVER, ABSOFT CORPORATION MAKES NO REPRESENTATION OFWARRANTIES WITH RESPECT TO THE PROGRAM MATERIAL DESCRIBED HEREIN ANDSPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTIES OF MERCHANTABILITY ORFITNESS FOR ANY PARTICULAR PURPOSE. FURTHER, ABSOFT RESERVES THE RIGHT TOREVISE THE PROGRAM MATERIAL AND MAKE CHANGES THEREIN FROM TIME TO TIMEWITHOUT OBLIGATION TO NOTIFY THE PURCHASER OF THE REVISION OR CHANGES. INNO EVENT SHALL ABSOFT BE LIABLE FOR ANY INCIDENTAL, INDIRECT, SPECIAL ORCONSEQUENTIAL DAMAGES ARISING OUT OF THE PURCHASER'S USE OF THE PROGRAMMATERIAL.
U.S. GOVERNMENT RESTRICTED RIGHTS — The software and documentation are provided withRESTRICTED RIGHTS. Use, duplication, or disclosure by the Government is subject to restrictions setforth in subparagraph (c) (1) (ii) of the Rights in Technical Data and Computer Software clause at252.227-7013. The contractor is Absoft Corporation, 2781 Bond Street, Rochester Hills, Michigan 48309.
ABSOFT CORPORATION AND ITS LICENSOR(S) MAKE NO WARRANTIES, EXPRESS ORIMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OFMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THESOFTWARE. ABSOFT AND ITS LICENSOR(S) DO NOT WARRANT, GUARANTEE OR MAKE ANYREPRESENTATIONS REGARDING THE USE OR THE RESULTS OF THE USE OF THESOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY, CURRENTNESS,OR OTHERWISE. THE ENTIRE RISK AS TO THE RESULTS AND PERFORMANCE OF THESOFTWARE IS ASSUMED BY YOU. THE EXCLUSION OF IMPLIED WARRANTIES IS NOTPERMITTED BY SOME STATES. THE ABOVE EXCLUSION MAY NOT APPLY TO YOU.
IN NO EVENT WILL ABSOFT, ITS DIRECTORS, OFFICERS, EMPLOYEES OR LICENSOR(S) BELIABLE TO YOU FOR ANY CONSEQUENTIAL, INCIDENTAL OR INDIRECT DAMAGES (INCLUDINGDAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESSINFORMATION, AND THE LIKE) ARISING OUT OF THE USE OR INABILITY TO USE THESOFTWARE EVEN IF ABSOFT HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.BECAUSE SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FORCONSEQUENTIAL OR INCIDENTAL DAMAGES, THE ABOVE LIMITATIONS MAY NOT APPLY TOYOU. Absoft and its licensor(s) liability to you for actual damages for any cause whatsoever, and regardless ofthe form of the action (whether in contract, tort, (including negligence), product liability or otherwise), will belimited to $50.
Absoft, the Absoft logo, Fx, and MacFortran are trademarks of Absoft CorporationApple, 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 ReservedPrinted 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.............................................................................................................1Absoft Fortran 90/95 ..................................................................................................................................1Absoft FORTRAN 77 ................................................................................................................................1Absoft C/C++ .............................................................................................................................................2
The Macintosh Programmer's Workshop ..................................................................................................2
Compatibility .................................................................................................................................................3
Conventions Used in this Manual ................................................................................................................3
Road Maps .....................................................................................................................................................3Fortran Road Maps.....................................................................................................................................4Macintosh Programming Road Map...........................................................................................................4
Year 2000 Problem........................................................................................................................................7Fortran 90/95 DATE_AND_TIME Subroutine............................................................................................7Unix Compatibility Library ........................................................................................................................7
CHAPTER 2 GETTING STARTED ..................................................................... 9
Introduction to MPW and Absoft Pro Fortran ..........................................................................................9
Starting an MPW Session.............................................................................................................................9
The MPW Environment .............................................................................................................................10Using the Menus.......................................................................................................................................11Using the Worksheet ................................................................................................................................11Executing Commands from the Worksheet..............................................................................................11The Commando Interface .........................................................................................................................12
Working with Source Files .........................................................................................................................13Editing 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 ............................................................................................................................. 21File Menu................................................................................................................................................. 21
New…( N)........................................................................................................................................ 21Open…( O) ...................................................................................................................................... 22Open Selection ( D) .......................................................................................................................... 22Close ( W) ........................................................................................................................................ 22Save ( S)........................................................................................................................................... 22Save as… ............................................................................................................................................ 22Save a Copy… .................................................................................................................................... 23Revert to Saved ................................................................................................................................... 23Page Setup…....................................................................................................................................... 23Print Window...................................................................................................................................... 23Quit ( Q) ........................................................................................................................................... 23
Edit Menu ................................................................................................................................................ 23Undo ( Z) .......................................................................................................................................... 23Cut ( X)............................................................................................................................................. 23Copy ( C).......................................................................................................................................... 24Paste ( V) .......................................................................................................................................... 24Clear.................................................................................................................................................... 24Select All ( A)................................................................................................................................... 24Show Clipboard .................................................................................................................................. 24Format… ( Y) ................................................................................................................................... 24Align ................................................................................................................................................... 25Shift Left and Shift Right ( [ and ]) .............................................................................................. 25
Find Menu................................................................................................................................................ 25Find… ( F) ....................................................................................................................................... 25
Searching for Line Numbers .......................................................................................................... 25Searching for Text.......................................................................................................................... 26
Find Same ( G) ................................................................................................................................. 27Find Selection ( H) ........................................................................................................................... 27Display Selection ................................................................................................................................ 27Replace… ( R).................................................................................................................................. 28Replace Same ( T) ............................................................................................................................ 28Next Error ( ≥).................................................................................................................................. 28Previous Error ( ≤)............................................................................................................................ 28
Mark Menu .............................................................................................................................................. 28Mark… ( M) ..................................................................................................................................... 29Unmark… ........................................................................................................................................... 29Browse… ............................................................................................................................................ 29Alphabetical ........................................................................................................................................ 30
Window Menu ......................................................................................................................................... 30Tile Windows...................................................................................................................................... 30Stack Windows ................................................................................................................................... 30
Directory Menu........................................................................................................................................ 30Show Directory ................................................................................................................................... 31Set Directory... .................................................................................................................................... 31
CHAPTER 4 USING THE WORKSHEET ......................................................... 33
The Worksheet Window ............................................................................................................................ 33
MPW Commands ....................................................................................................................................... 34Command Syntax..................................................................................................................................... 35Executing MPW Commands from the Worksheet................................................................................... 35
Table of Contents iii
Command Parameters...............................................................................................................................36Command Terminators .............................................................................................................................37Accessing the Commando Interface .........................................................................................................38Target and Active Windows.....................................................................................................................39Routing Command Output .......................................................................................................................39File Name Generation...............................................................................................................................41Using MPW Variables..............................................................................................................................42
User-Defined Variables .......................................................................................................................42Preassigned MPW Variables ...............................................................................................................43
Creating Scripts ........................................................................................................................................43Command Aliases.....................................................................................................................................44Structured Commands ..............................................................................................................................45Command Execution ................................................................................................................................45Special Characters ....................................................................................................................................45
The ∂ Character....................................................................................................................................46The § Character ...................................................................................................................................46
MPW Command Reference........................................................................................................................46Finder commands .....................................................................................................................................46
NewFolder ...........................................................................................................................................47Files .....................................................................................................................................................47Delete...................................................................................................................................................48Duplicate..............................................................................................................................................48Eject .....................................................................................................................................................49Flush ....................................................................................................................................................49Move....................................................................................................................................................49WhereIs................................................................................................................................................49Volumes...............................................................................................................................................50Rename ................................................................................................................................................50Choose .................................................................................................................................................51
File-related commands .............................................................................................................................51SetFile..................................................................................................................................................51Catenate ...............................................................................................................................................52Search ..................................................................................................................................................52Find......................................................................................................................................................53Translate ..............................................................................................................................................53Sort ......................................................................................................................................................53EnTab...................................................................................................................................................54Count ...................................................................................................................................................54Compare...............................................................................................................................................55CompareFiles.......................................................................................................................................55Equal....................................................................................................................................................56Adjust ..................................................................................................................................................56Clear.....................................................................................................................................................56Copy.....................................................................................................................................................57
Help commands ........................................................................................................................................57GetErrorText........................................................................................................................................57Help .....................................................................................................................................................58
MPW Environment commands ................................................................................................................58AddMenu .............................................................................................................................................58DeleteMenu .........................................................................................................................................59Date......................................................................................................................................................59Set ........................................................................................................................................................60UnSet ...................................................................................................................................................60Directory..............................................................................................................................................60SetDirectory.........................................................................................................................................61Alias.....................................................................................................................................................61
iv Fortran User Guide
Align ................................................................................................................................................... 61Unalias ................................................................................................................................................ 62Mark.................................................................................................................................................... 62Unmark ............................................................................................................................................... 62Commando.......................................................................................................................................... 62DumpFile ............................................................................................................................................ 63Request................................................................................................................................................ 63GetFileName ....................................................................................................................................... 64Confirm............................................................................................................................................... 64Alert .................................................................................................................................................... 64Quit ..................................................................................................................................................... 64Shutdown ............................................................................................................................................ 65Beep .................................................................................................................................................... 65
Window commands ................................................................................................................................. 65New..................................................................................................................................................... 66Open.................................................................................................................................................... 66Close ................................................................................................................................................... 66Print..................................................................................................................................................... 67Line ..................................................................................................................................................... 67Target .................................................................................................................................................. 67File ...................................................................................................................................................... 68Windows ............................................................................................................................................. 68TileWindows....................................................................................................................................... 68ZoomWindows.................................................................................................................................... 68MoveWindow ..................................................................................................................................... 69SizeWindow........................................................................................................................................ 69RotateWindows................................................................................................................................... 69
CHAPTER 5 USING THE COMPILER ............................................................. 71
Compiling Programs .................................................................................................................................. 71Using the Worksheet................................................................................................................................ 71Using the Tools Menu ............................................................................................................................. 72
The Absoft Tools Commando Interface ................................................................................................... 73Source Files Dialog Box.......................................................................................................................... 74Include Path(s) (-I)................................................................................................................................... 74Libraries…............................................................................................................................................... 76
Unix Compatibility Library................................................................................................................. 76VAX/VMS Compatibility Library ...................................................................................................... 76IMSL MATH/STAT Library .............................................................................................................. 76LAPACK Linear Algebra Library ...................................................................................................... 77Other Libraries… ................................................................................................................................ 77
Text Boxes ............................................................................................................................................... 77Executable Filename ........................................................................................................................... 77Command Line Box ............................................................................................................................ 78Help Box ............................................................................................................................................. 78
Buttons and Compiler Options ................................................................................................................ 78Output File Box................................................................................................................................... 78Main Program Box.............................................................................................................................. 79The Compile Button............................................................................................................................ 79General Option Buttons ...................................................................................................................... 79
Errors While Compiling ............................................................................................................................ 79GetErrorText command ........................................................................................................................... 80
Table of Contents v
Absoft Fortran 90/95 Options ....................................................................................................................81COMPILER CONTROL... .......................................................................................................................82
Suppress warnings (-w) .......................................................................................................................83Frequent Command-Period checks (-N9) ............................................................................................83Show progress (-v)...............................................................................................................................83Use 32-bit branches (-N11) .................................................................................................................83Output Version number (-V)................................................................................................................84Stop on error (-ea)...............................................................................................................................84Allow greater than 100 errors (-dq).....................................................................................................84Default Recursion (-eR) ......................................................................................................................84Use files for temporary storage (-F) ....................................................................................................84Warn of non-standard usage (-en).......................................................................................................84Warning level (-znn) ...........................................................................................................................85Suppress Warning number(s) (-Znn)...................................................................................................85Generate profiler information (-profile) ..............................................................................................85Generate procedure trace (-N80) .........................................................................................................85
OPTIMIZATIONS… ...............................................................................................................................85Optimizations (-O)...............................................................................................................................86
COMPATIBILITY…...............................................................................................................................86Source Formats ....................................................................................................................................87
Free-Form (-f free) .........................................................................................................................87Fixed-Form (-f fixed) ......................................................................................................................87Fixed line length (-W nn) ...............................................................................................................87
Promote REAL and COMPLEX (-N113) ...........................................................................................87Demote Double Precision to Real (-dp) ..............................................................................................87Static storage (-s).................................................................................................................................87Disable compiler directive (-xdirective) .............................................................................................88INTEGER*2 and LOGICAL*2 (-i2)...................................................................................................88INTEGER*8 and LOGICAL*8 (-i8)...................................................................................................88One trip DO loops (-ej) .......................................................................................................................88Max Internal Handle (-T nn) ...............................................................................................................89Temporary string size (-t nn)...............................................................................................................89
Module File Path(s) (-p)...........................................................................................................................90Module File(s) (-p) ...................................................................................................................................90MISCELLANEOUS….............................................................................................................................91
Escape Sequences in Strings (-YCSLASH=1)....................................................................................92No Dot for Percent (-YNDFP=1)........................................................................................................92COMMON Block Name Character Case (-YCOM_NAMES={ ASIS | UCS | LCS})......................92COMMON Block Name Prefix (-YCOM_PFX=string) ....................................................................92COMMON Block Name Suffix (-YCOM_SFX=string) ....................................................................92Check Array Boundaries (-Rb) ...........................................................................................................93Check Array Conformance (-Rc) ........................................................................................................93Check Substrings (-Rs) .......................................................................................................................93Check Pointers (-Rp) ...........................................................................................................................93YEXT_NAMES={ASIS | UCS | LCS} ...............................................................................................93External Symbol Suffix (-YEXT_SFX=string) ..................................................................................93
Other F90/95 Options...............................................................................................................................93-YDEALLOC= {MINE | ALL | CACHE}) .........................................................................................94YPEI={0|1} .........................................................................................................................................94
Absoft Fortran 90/95 Compiler Directives................................................................................................94NAME Directive ......................................................................................................................................95FREE Directive ........................................................................................................................................95FIXED Directive ......................................................................................................................................95STACK Directive .....................................................................................................................................96
Absoft Fortran 77 Options .........................................................................................................................96
vi Fortran User Guide
COMPILER CONTROL... ...................................................................................................................... 97Suppress warnings (-w)....................................................................................................................... 97Suppress alignment warnings (-A) ...................................................................................................... 97Use 32-bit branches (-N11) ................................................................................................................ 98Generate procedure trace (-N124) ...................................................................................................... 98Generate profiler information (-p) ...................................................................................................... 98Check array boundaries (-C)............................................................................................................... 98Full Debug with Fx (-g) ...................................................................................................................... 98Min Debug with Fx (-gmin) ............................................................................................................... 98Info for unused structures (-N111)..................................................................................................... 99Suppress delayed stores (-m) .............................................................................................................. 99Conditional compilation (-x)............................................................................................................... 99Max Internal Handle (-T nn) .............................................................................................................. 99Output ............................................................................................................................................... 100No compiler standard output (-q)...................................................................................................... 100Show progress (-v) ............................................................................................................................ 100Frequent Command-Period checks (-N9) ......................................................................................... 101Use files for temporary storage (-F) ................................................................................................. 101Define Compiler directives (-Dname[=value]) ............................................................................... 101Generate object files (-c) .................................................................................................................. 101Specifying the executable file name (-o name) ............................................................................... 101
OPTIMIZATIONS… ............................................................................................................................ 102Basic optimizations (-O) ................................................................................................................... 102DATA treated as constants (-N5) ..................................................................................................... 102Function decomposition (-N18)........................................................................................................ 103Loop unrolling (-U and -h nn and -H nn) ........................................................................................ 103
COMPATIBILITY… ............................................................................................................................ 104Folding to lower case (-f) .................................................................................................................. 105Static storage (-s) .............................................................................................................................. 105Use record lengths in I/O (-N3) ........................................................................................................ 105RECL Defines 32-bit words (-N51) ................................................................................................. 105Folding to upper case (-N109) ......................................................................................................... 105
One-trip DO loops (-d)................................................................................................................. 106INTEGER*2 and LOGICAL*2 (-i2 ) ............................................................................................... 106INTEGER*8 and LOGICAL*8 (-i8 ) ............................................................................................... 106Zero extend INTEGER*1 (-N102)................................................................................................... 106Warn of non-ANSI usage (-N32) ..................................................................................................... 106Extern Globals (-M) .......................................................................................................................... 106Source Formats ................................................................................................................................. 107
Fortran 90 Free-Form (-8)............................................................................................................ 107IBM VS Free Form (-N112) ........................................................................................................ 107VAX Tab-Format (-V) ................................................................................................................. 107Wide format (-W)......................................................................................................................... 107
Set Big-Endian (-N26)...................................................................................................................... 107Set Little-Endian (-N27)................................................................................................................... 107Set COMMON block name (-N22) .................................................................................................. 107Evaluate left-to-right (-N20)............................................................................................................. 108Don’t generate FMA instructions (-Q51) ......................................................................................... 108Double precision transcendentals (-N2) ........................................................................................... 108Sign extend BYTE() & WORD() (-N7) ........................................................................................... 109DATA variables are static (-N1)....................................................................................................... 109Promote REAL and COMPLEX (-N113) ........................................................................................ 109Escape sequences in strings (-K)....................................................................................................... 109Allows CASE without DEFAULT (-N4) ......................................................................................... 109Allows UNIT= without FMT= (-N16) ............................................................................................. 109Align COMMON variables (-N34) .................................................................................................. 109Pascal keyword significant (-N17) ................................................................................................... 110
Table of Contents vii
Pascal declaration is error (-N21)......................................................................................................110Append underscore to names (-N15) ................................................................................................110Temporary string size (-t nn).............................................................................................................110STRUCTURE Alignment ..................................................................................................................110
Align STRUCTURE fields to 1 byte boundaries (-N56)..............................................................110Align STRUCTURE fields to 2 byte boundaries (-N57)..............................................................111Align STRUCTURE fields to 4 byte boundaries (-N58)..............................................................111Align STRUCTURE fields to 8 byte boundaries (-N59)..............................................................111
Other F77 Options ..................................................................................................................................111Warnings for Undeclared Variables (-N114) ....................................................................................111Pad Source Lines (-N115).................................................................................................................111Debug with Fx (-g) ............................................................................................................................111Don’t Mangle COMMON Block Name (-N110) ..............................................................................111
Absoft C/C++ Options ..............................................................................................................................112Optimizations (-O) .................................................................................................................................112Source Formats.......................................................................................................................................112
ARM C++ (-Tp) ................................................................................................................................112Draft Std C++ (-std) ..........................................................................................................................113ANSI C (-A).......................................................................................................................................113K and R C (-K)...................................................................................................................................113
COMPILER CONTROL... .....................................................................................................................113Use long branches (-N18) .................................................................................................................113No inlines (-inline none) ..................................................................................................................114Use temporary files (!N61)................................................................................................................114Profiler Information (-p)....................................................................................................................114Procedure Trace (-N124) ..................................................................................................................114Exception Handling (-except on|off) ...............................................................................................114Error and Diagnostic Messages .........................................................................................................114Suppress all warnings (-w31) ............................................................................................................115Suppress warnings (-w16) .................................................................................................................115Suppress informationals (-w8) ..........................................................................................................115Suppress anachronisms (-w2)............................................................................................................115Suppress template warnings (-w1) ....................................................................................................115Treat anachronisms as errors (-wp) ...................................................................................................115Treat all warnings as errors (-wabort)...............................................................................................115Max errors (-maxerr n) .....................................................................................................................115
COMPATIBILITY….............................................................................................................................116Suppress Apple extensions (-appleext off).......................................................................................116Use int enums (-enum min|int).........................................................................................................116Use 68k alignment (-align mac68k|power).....................................................................................116Make chars unsigned (-char signed|unsigned) ..............................................................................117Munch…............................................................................................................................................117
Set initialization prefix (-init prefix) .............................................................................................117Set termination prefix (-term prefix)............................................................................................117
PREPROCESSOR…..............................................................................................................................118Defines (-d name[=value]) ..............................................................................................................118Undefines (-u name).........................................................................................................................118Preprocess to file (-P)........................................................................................................................119Preprocess to stdout (-E) ...................................................................................................................119Include tree to stderr (-H) ..................................................................................................................119Verbose (-v) .......................................................................................................................................119Verbose templates (-ptv) ...................................................................................................................119Quiet (-q) ...........................................................................................................................................119
CHAPTER 6 PORTING CODE........................................................................ 121
viii Fortran User Guide
Porting Code from VAX .......................................................................................................................... 121Compile Time Options and Issues ......................................................................................................... 122Runtime Issues....................................................................................................................................... 123
Porting Code from IBM VS FORTRAN ................................................................................................ 123Compile-time Options and Issues .......................................................................................................... 124Run-time Issues ..................................................................................................................................... 124
Porting Code From Microsoft FORTRAN (PC version) ...................................................................... 124Compile-time Options and Issues .......................................................................................................... 125
Porting Code from Sun Workstations .................................................................................................... 126Compile-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 ................................................................................ 127Language Systems Fortran..................................................................................................................... 127Other Absoft Compilers......................................................................................................................... 127
Other Porting Issues................................................................................................................................. 128Memory Management............................................................................................................................ 128Stack Issues............................................................................................................................................ 130File and Path Names .............................................................................................................................. 131Tab Character Size................................................................................................................................. 133Floating Point Math Control .................................................................................................................. 133
Rounding Direction........................................................................................................................... 134Exception Handling .......................................................................................................................... 134
CHAPTER 7 BUILDING PROGRAMS ........................................................... 135
An Overview of Program Building ......................................................................................................... 135The Components of an Application ....................................................................................................... 135Working with Resources........................................................................................................................ 136File types and creators ........................................................................................................................... 136
Creating Object Files ............................................................................................................................... 136Fsplit - Source Code Splitting Utility .................................................................................................... 138Ftnchek - ANSI Compliance Utility ...................................................................................................... 139
Linking Programs for PowerPC ............................................................................................................. 140
Building Programs.................................................................................................................................... 143Creating Makefiles................................................................................................................................. 144Modifying Makefiles ............................................................................................................................. 144
Format of a Makefile......................................................................................................................... 144Create Build Commands ................................................................................................................... 145ACM Command.................................................................................................................................. 146Build ( B)........................................................................................................................................ 147BuildProgram command ................................................................................................................... 147Make Command................................................................................................................................ 147
Table of Contents ix
The Snowflake program .........................................................................................................................149
Creating Libraries for PowerPC..............................................................................................................150
Working with Resources...........................................................................................................................151Include Files ...........................................................................................................................................153Adding an Icon to an Application ..........................................................................................................153The SIZE(-1) Resource ..........................................................................................................................155
Creating a Tool Using Absoft Pro Fortran .............................................................................................156Tool Initialization ...................................................................................................................................158Memory Management.............................................................................................................................158
CHAPTER 8 THE MACINTOSH RUNTIME WINDOW ENVIRONMENT..... 159
Using MRWE.............................................................................................................................................159The MRWE Window..............................................................................................................................160How Your Program And MRWE Work Together .................................................................................161Working With Text in MRWE...............................................................................................................162Using THE MRWE Default Menus .......................................................................................................162File Menu ...............................................................................................................................................162
Save ( S)..........................................................................................................................................162Save As…..........................................................................................................................................163Page Setup… .....................................................................................................................................163Print Window…( P)........................................................................................................................163Quit ( Q)..........................................................................................................................................163
Edit Menu ...............................................................................................................................................163Undo ( Z).........................................................................................................................................163Cut ( X)............................................................................................................................................163Copy ( C) ........................................................................................................................................163Paste ( V) .........................................................................................................................................164Clear...................................................................................................................................................164
Font and Size Menus ..............................................................................................................................164
Programming with MRWE......................................................................................................................164Program Organization: Fortran VS. Macintosh......................................................................................164
MRWE Event Loop Operation ..........................................................................................................166Customizing Menus................................................................................................................................167
Adding Menus ...................................................................................................................................167Special Characters .............................................................................................................................168Menus and the READ statement........................................................................................................168Removing a Menu or Menu Item.......................................................................................................169Menu Response Routines and mrwe_DoMenu ................................................................................169Adding Checkmarks to Menus ..........................................................................................................170Enabling/Disabling Menu Items ........................................................................................................170
Launching OTHER APPLICATIONS ...................................................................................................171Apple Events ..........................................................................................................................................172
Apple Event Target............................................................................................................................173Apple Event Class and ID..................................................................................................................173Extra Information in an Apple Event.................................................................................................173Receiving Apple Events ....................................................................................................................176Error Codes Returned from Apple Event Routines ...........................................................................179Other Examples of Apple Events.......................................................................................................179
Sending a request to the Finder.....................................................................................................179Using other standard Apple Events...............................................................................................181Sending information between MRWE applications......................................................................181
x Fortran User Guide
Scripting ....................................................................................................................................... 181Further Information About Apple Events ......................................................................................... 182
Creating Multiple Windows................................................................................................................... 182Showing Alert Messages ....................................................................................................................... 183The SetPrefs Tool .................................................................................................................................. 184
Applications to affect ........................................................................................................................ 185End of execution ............................................................................................................................... 185Window characteristics ..................................................................................................................... 185Window name (-savename name) ............................................................................................ 185Close box (-closebox)................................................................................................................ 185Window Size (-windowsize normal|maximize) ............................................................... 186Text characteristics ........................................................................................................................... 186Memory requirements ....................................................................................................................... 186Timer interval.................................................................................................................................... 187Timer (-timer 60ths-of-a-second) ..................................................................................... 187File characteristics............................................................................................................................. 187
CHAPTER 9 MACINTOSH PROGRAMMING ............................................... 189
Using the Macintosh Toolbox .................................................................................................................. 190How Absoft Fortran 90/95 Interfaces with the Toolbox........................................................................ 191How Absoft Fortran 77 Interfaces with the Toolbox............................................................................. 191Locating the Fortran 90/95 and FORTRAN 77 Interface Files ............................................................. 192Passing Arguments ................................................................................................................................ 193IMPLICIT NONE Statement ................................................................................................................. 195Initialization Routines Called by Pro Fortran Startup............................................................................ 195Using MRWE and the Toolbox ............................................................................................................. 196Using STRUCTUREs and RECORDs with Toolbox............................................................................ 196Passing the Toolbox a Pointer to a Fortran Routine .............................................................................. 197Handles .................................................................................................................................................. 199Accessing the Quickdraw Globals......................................................................................................... 201Apple Events.......................................................................................................................................... 201
Macintosh Toolbox Examples ................................................................................................................. 206
Interfacing with Other Languages.......................................................................................................... 206Interfacing with C .................................................................................................................................. 207
Fortran Data Types in C.................................................................................................................... 207Passing Values Between C and Fortran ............................................................................................ 207
Reference parameters ................................................................................................................... 208Value parameters.......................................................................................................................... 209
Array Parameters............................................................................................................................... 210Function Results................................................................................................................................ 210Passing Strings to C .......................................................................................................................... 211Calling Fortran math routines ........................................................................................................... 211Accessing COMMON blocks from C............................................................................................... 212
Interfacing with Pascal .......................................................................................................................... 212Fortran Data Types in Pascal ............................................................................................................ 213Setting up Inter-Language Calls ....................................................................................................... 213
Declaring Pascal routines to be called from Fortran .................................................................... 214Declaring Fortran routines to be called from Pascal .................................................................... 215
Passing Values Between Pascal and Fortran..................................................................................... 215Reference parameters ................................................................................................................... 216Value parameters.......................................................................................................................... 217
Function Results................................................................................................................................ 218Passing Strings to Pascal................................................................................................................... 219
Table of Contents xi
Calling Fortran math routines ............................................................................................................219Interfacing with Assembly Language.....................................................................................................220The Fortran Stack Frame ........................................................................................................................220Function Results .....................................................................................................................................221
Resources ...................................................................................................................................................221Include Files ...........................................................................................................................................222Adding an Icon to an Application ..........................................................................................................222The SIZE(-1) Resource ..........................................................................................................................224Compiling a Resource Description File..................................................................................................225
Debugging ..................................................................................................................................................225Compiler Options ...................................................................................................................................225Linker Options........................................................................................................................................225Size Resource .........................................................................................................................................225
Profiling......................................................................................................................................................226Compiler Options ...................................................................................................................................226Linker Options........................................................................................................................................226Size Resource .........................................................................................................................................226
CHAPTER 10 USING THE FX DEBUGGER ................................................... 227
Introduction To Fx....................................................................................................................................227How To Use This Chapter......................................................................................................................227
Preparing For Debugging.........................................................................................................................228Compiler Options ...................................................................................................................................228Linker Options........................................................................................................................................230Size(-1) Resource ...................................................................................................................................230System Folder Additions ........................................................................................................................231Starting A Debugging Session................................................................................................................231
Debugging Concepts..................................................................................................................................233Getting Started........................................................................................................................................233Single Stepping.......................................................................................................................................234Using Breakpoints ..................................................................................................................................234Displaying Variables ..............................................................................................................................236Changing Variables ................................................................................................................................240Debugging Hints.....................................................................................................................................240
Fx Menus and Windows ...........................................................................................................................241File Menu ...............................................................................................................................................241
New Source ( N) .............................................................................................................................241Open… ( O) ....................................................................................................................................241Open Workspace…............................................................................................................................241Add Path… ........................................................................................................................................242Close ( W) .......................................................................................................................................242Save Workspace ................................................................................................................................242Save Window Positions .....................................................................................................................242Quit ( Q)..........................................................................................................................................242
Edit Menu ...............................................................................................................................................242Undo ( Z).........................................................................................................................................243Cut ( X)............................................................................................................................................243Copy ( C) ........................................................................................................................................243Paste ( V) .........................................................................................................................................243
xii Fortran User Guide
Clear.................................................................................................................................................. 243Select All ( A)................................................................................................................................. 243Preferences........................................................................................................................................ 243
Environment................................................................................................................................. 243Format .......................................................................................................................................... 244Startup .......................................................................................................................................... 245
Control Menu......................................................................................................................................... 246Continue ( J)................................................................................................................................... 246Kill ( K) .......................................................................................................................................... 246Stop ................................................................................................................................................... 246Restart ............................................................................................................................................... 246Return ( R) ..................................................................................................................................... 246Step Into ( I).................................................................................................................................... 247Step Over ( S)................................................................................................................................. 247Run To ( T)..................................................................................................................................... 247Down ( [) ....................................................................................................................................... 247Home ( H)....................................................................................................................................... 247Up ( ]) ............................................................................................................................................. 248Clear All Breakpoints........................................................................................................................ 248Show Program Counter ( P) ........................................................................................................... 248
View Menu ............................................................................................................................................ 248Address… ......................................................................................................................................... 249Line… ............................................................................................................................................... 249Next ( 9) ......................................................................................................................................... 249Prev ( 0).......................................................................................................................................... 249Globals .............................................................................................................................................. 249Locals................................................................................................................................................ 249Statics................................................................................................................................................ 250Types................................................................................................................................................. 250Change… .......................................................................................................................................... 250View As… ........................................................................................................................................ 250Code For “” ....................................................................................................................................... 250
Actions Menu......................................................................................................................................... 251Find… ( F) ..................................................................................................................................... 251Find Again ( G) .............................................................................................................................. 251Print “” ( E) .................................................................................................................................... 251Print * “” ( D) ................................................................................................................................. 251Print As… ......................................................................................................................................... 252Watch “” ........................................................................................................................................... 252Watch * “” ........................................................................................................................................ 252Watch All .......................................................................................................................................... 252Watch As…....................................................................................................................................... 253Watch Locals .................................................................................................................................... 253Set Breakpoint On “” ........................................................................................................................ 253
Profile Menu .......................................................................................................................................... 253Configure… ...................................................................................................................................... 253On...................................................................................................................................................... 253profmt…............................................................................................................................................ 254
Windows Menu...................................................................................................................................... 254Hide Toolbar/Show Toolbar ............................................................................................................. 254Tile .................................................................................................................................................... 254Cascade ............................................................................................................................................. 254Assembly ( 1) ................................................................................................................................. 254Breakpoints ( 2).............................................................................................................................. 255Classes ( 3) ..................................................................................................................................... 256Code ( 4)......................................................................................................................................... 257Memory ( 5) ................................................................................................................................... 257
Table of Contents xiii
General Registers ( 6) .....................................................................................................................258FPU Registers ....................................................................................................................................259Stack ( 7) .........................................................................................................................................259Symbols ( 8)....................................................................................................................................259
Profiling......................................................................................................................................................260Options For Profiling..............................................................................................................................260
Compiler Options...............................................................................................................................260Linker Options...................................................................................................................................261
Profiling With Fx....................................................................................................................................261Using Profmt ..........................................................................................................................................262
File Menu...........................................................................................................................................263Open… ( O) ...............................................................................................................................263Close ( W) ..................................................................................................................................263Info ( I) .......................................................................................................................................263Page Setup….................................................................................................................................263Print… ( P).................................................................................................................................263Quit ( Q) .....................................................................................................................................264
Edit Menu ..........................................................................................................................................264Undo ( Z)....................................................................................................................................264Cut ( X).......................................................................................................................................264Copy ( C)....................................................................................................................................264Paste ( V) ....................................................................................................................................264Clear..............................................................................................................................................264Hide Time .....................................................................................................................................264Hide Calls .....................................................................................................................................265Hide Time/Call..............................................................................................................................265Hide Graph....................................................................................................................................265
Sort Menu ..........................................................................................................................................265By Name .......................................................................................................................................265By Time ........................................................................................................................................265By Calls.........................................................................................................................................265By Time/Call.................................................................................................................................265Ascending .....................................................................................................................................266Descending....................................................................................................................................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
Fortran User Guide
CHAPTER 1
Introduction
INTRODUCTION TO ABSOFT PRO FORTRAN
Absoft specializes in the development of Fortran compilers and related tools. Fullimplementations 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'sFortran programmers who are moving code to their desktop, to link Fortran code with Clibraries. To facilitate this process, certain Absoft Fortran implementations also include aC/C++ compiler, allowing users to create mixed Fortran/C applications from within asingle development environment.
This User Guide is designed for Pro Fortran. It explains the operation of Absoft Fortran90/95, Absoft FORTRAN 77, and Absoft C/C++. In the event you have licensed only oneof these compilers, please refer only to the appropriate section(s) and disregard theothers. All compilers operate in a similar manner, share a common tool set, are linkcompatible, and are invoked from a common user interface. A brief summary of eachcompiler appears below.
Absoft Fortran 90/95
A complete ANSI Fortran 90/95 implementation plus extensions. Absoft Fortran 90/95 isthe result of a five year joint development effort with Cray Research. It utilizes a versionof the CF90 front-end and is source compatible with several Cray F90 releases. Itprovides full support for the Macintosh API, the toolbox, directly from Fortran and iscapable of building shared libraries. Several popular VAX and workstation extensionshave also been added.
Absoft FORTRAN 77
Refined over 16 years, with emphasis on porting legacy code from workstations. AbsoftFortran 77 is full ANSI 77 with MIL-STD-1753, Cray-style POINTERs, plus mostextensions from VAX FORTRAN as well as many from IBM, Sun, HP, and Cray. AbsoftFortran 77 supports legacy extensions that are not part of the Fortran 90/95 standard. Seethe chapter on Porting Code in this manual for further information. Fortran 77 is fullylink compatible with Fortran 90/95 and C/C++ so existing, extended FORTRAN 77routines can be easily compiled and linked with new Fortran 90/95 or C/C++ code. Theentire Macintosh toolbox is supported and shared libraries can be created directly fromFortran.
2 Introduction
Fortran User Guide
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 toolboxis supported and shared libraries can be created from C and C++.
Absoft Pro Fortran implementations include all of the tools necessary for you to createstand-alone, double-clickable Macintosh applications. The purpose of this User Guide isto offer step-by-step instructions on the operation of each compiler, writing, compiling,debugging, linking and running your program. MRWE, Absoft's application frameworkcan automatically build a standard Macintosh interface for each compiled application.MRWE is written entirely in Fortran and the complete source code is included as anexample 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 efficientdevelopment. Pro Fortran is designed to operate with the same high quality tools used byApple's own engineers: tools written and maintained by Apple to provide the highestquality development environment for programmers using the Macintosh. By followingthe standards established by Apple, Absoft Fortran 77, Fortran 90/95, C and C++ workwith 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 MacintoshProgrammer’s Workshop (MPW), an integrated environment that is easy on beginnersand a blessing to experienced programmers. Since Absoft Pro Fortran works withinMPW, a few things should be noted:
• MPW is itself an application. You can double-click on the MPW Shellicon to launch it or you can open MPW document files (FORTRANsource files) to launch MPW and use the compiler.
• There is always a Worksheet window that displays compiler messagesand any errors. As you enter text into the Worksheet, the contents areautomatically saved between sessions. The Worksheet should beperiodically cleared, since it can grow quite large.
• The Return and Enter keys have very different meanings in the MPWenvironment. The Return key moves to the next line while the Enterkey executes MPW commands.
Introduction 3
Fortran User Guide
COMPATIBILITY
Absoft Pro Fortran for the PowerPC has excellent mainframe compatibility. Most popularVAX/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 forPowerPC is 100% source-compatible with other Absoft compilers for Macintosh,Windows 95/98, Windows NT, and Intel-based Linux workstations. See the chapterPorting Code for additional compatibility information.
CONVENTIONS USED IN THIS MANUAL
There are a few typographic and syntactic conventions used throughout this manual forclarity.
• [] 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 asin 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 arereferenced as in the following:
Option-W (hold the Option key and press W)Command-period (hold the Command key and press '.')
-. (same, is the Command key symbol)
• Unless otherwise indicated, all numbers are in decimal form.
• FORTRAN examples appear in the following form:
PROGRAM SAMPLEWRITE(9,*) "Hello World!"END
ROAD MAPS
Although this manual contains all the information needed to write programs with AbsoftPro Fortran on the Macintosh, there are a number of other manuals that describe Fortran
4 Introduction
Fortran User Guide
90/95, FORTRAN 77, and C/C++ extensions; the Macintosh Programmer's Workshop(MPW) and the Macintosh toolbox; and Macintosh programming in further detail. Thetwo road maps in this chapter will guide you to these manuals for introductory oradvanced reference. The bibliography in appendices lists further information about eachmanual.
Fortran Road Maps
The Absoft implementation of Fortran 90/95 is detailed in the online manual, Fortran 90Concise Reference, in the Documentation folder of the Pro Fortran CDROM. FORTRAN77 is detailed in the online manual, FORTRAN 77 Language Reference Manual, also inthe Documentation folder of the Pro Fortran CDROM. A discussion of floating pointprecision is at the end of the chapter Porting Code. Figures 1-1 shows additionalmanuals that can be used for referencing the FORTRAN language and internal mathoperations.
ANSI C StandardANSI X3.159-1989
Annotated C++ Reference ManualEllis and Stroustrup
ANSI FORTRAN 77 StandardANSI X3.9-1978
ANSI Fortran 90 StandardANSI X3.198-1992
IEEE Floating Point StandardP754
Inside Macintosh: RISC NumericsApple Computer, Inc
Apple Numerics Manual(SANE)
Absoft Fortran User Guide
FORTRAN 77 language road mapFigure 1-2
Macintosh Programming Road Map
Absoft Pro Fortran provides complete access to the Macintosh toolbox routines, both inthe traditional or ‘Classic’ interface as well as the new ‘Carbon’ interface. This manualdescribes the interface to these routines, but does not describe each of the thousands of
Introduction 5
Fortran User Guide
routines available. Programmers wishing to make use of these routines to add graphics totheir programs or to extend the user interface provided by MRWE, may wish to purchaseadditional documentation on the Macintosh toolbox. Figure 1-3 lists the documentationproduced by Apple.
Figure 1-2 is divided into three sections for different levels of Macintosh familiarity. Thefirst shows the books that introduce the Macintosh User Interface and general Macintoshprogramming concepts to Fortran programmers new to the Macintosh. The secondsection is the most likely starting place for Fortran programmers familiar with usingMacintosh applications. The last section is for programmers using languages such as C,Pascal, or assembly in conjunction with Absoft Pro Fortran.
6 Introduction
Fortran User Guide
Programmers new tothe Macintosh
Programmers familiarwith Macintoshconcepts
Programmers usingmultiple languages
������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
Human Interface Guidelines:The Apple Desktop Interface
Programmer's Introduction tothe Macintosh Family
Technical Introduction to theMacintosh Family
Absoft Fortran 77/90Language Reference Manuals
Inside Macintosh Volumes I-VI
Inside Macintosh:Risc System Software
Macintosh Technical Notes
Macintosh Programmer'sWorkshop (MPW) Reference
MPW Assembler ReferenceMPW C & Pascal ReferenceManuals
Macintosh programming road mapFigure 1-2
Introduction 7
Fortran User Guide
YEAR 2000 PROBLEM
All versions of Absoft Pro Fortran products for Macintosh, Power Macintosh, Windows95/98, Windows NT, Linux, and UNIX will operate correctly across the date transition tothe year 2000. Neither the compilers nor the runtime libraries have ever used 2-digityears in their internal operation. This means the version of Absoft Pro Fortran that youalready have will continue to operate correctly. No patches or version updates arerequired.
The only caveat may be for those porting code from VAX/VMS systems. Since the early1980s, Absoft Pro Fortran products have included software libraries designed to facilitateporting code from the VAX/VMS environment. Included in these VAX compatibilitylibraries 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 IDATEin a program that stores or compares dates, you may need to recode portions of yourapplication. 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 thedate and real time clock. Refer to the Fortran 90 Concise Reference for furtherinformation.
Unix Compatibility Library
There are a number of subroutines in the Unix Compatibility Library that return the dateand time in both INTEGER and CHARACTER format. Refer to the section AbsoftCompatibility Libraries at the end of the FORTRAN 77 Language Reference Manualfor information on their format and use.
9
Fortran User Guide
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 basicMacintosh skills, such as using menus and selecting with the mouse. Also, you should befamiliar with using windows, pop-up menus, dialog boxes and alert boxes. For moreinformation, consult the Macintosh Reference manual.
If you are familiar with MPW and would like to skip this chapter, use the table below tolocate 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 usersTable 2-1
INTRODUCTION TO MPW AND ABSOFT PRO FORTRAN
Absoft Pro Fortran is used within the Macintosh Programmer's Workshop (MPW). MPWprovides a powerful programming environment for programmers, including an integrated,window-based text-editing environment for the Absoft Pro Fortran compilers andextensive file manipulation capabilities. In addition to its many built-in commands, MPWalso 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 theMPW folder or double-click on any MPW document file. As you create and editFORTRAN source files within MPW, you save them as MPW documents.
10 Getting Started
Fortran User Guide
MPW iconsFigure 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 theMPW shell icon.
Double-click on the MPWshell 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 isthe Status Panel. When the MPW shell is not executing, the Status Panel displays thewords “MPW Shell.” At the top of the Worksheet window is the Title Bar that shows thedirectory of the Worksheet.
MPW environmentFigure 2-2
Source files may be created, edited and compiled from within MPW using its commandlanguage. To initiate a command from within MPW, use the menus or enter a commandline in an MPW window.
Getting Started 11
Fortran User Guide
Using the Menus
The menu bar is located at the top of the screen. MPW menus are the easiest way toexecute a command— simply select the command from the menu. The Tools menu isused to start the Absoft Pro Fortran compilers; other menus invoke commands forworking with source files, and specifying directories.
The MPW Editor, the set of editing commands in MPW, provides extensive capabilitiesto create and edit source files. A text window can be accessed to enter and edit files in thesame way that you would use a word processor. The MPW Editor is customized forprogramming 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. Simplyenter your text and separate lines of text with the Return key. If you want to edit yourtext, select a command from the menus.
Using the Worksheet
The Worksheet window is always open and accessible during an MPW session. Since itcannot be closed, you can use the Worksheet like a console to type in all of yourcommands and see the output. MPW commands can be initiated from any text windowhowever, the Worksheet is more useful for executing command lines.
By default, MPW command output is sent to the window where the command wasexecuted. For instance, the Help command sends information to the window, informationyou usually do not want to include in your text files. If you execute the Help command inthe Worksheet window, the help information is sent to the Worksheet window withoutaffecting the contents of a text window.
To execute an MPW command from the Worksheet, type in the name of the commandand press Enter. You can also use the Status Panel to execute a command: a mouse clickon the Status Panel is equivalent to pressing the Enter key. MPW commands arediscussed in the chapter Using the Worksheet; the entire MPW command language isdescribed in the MPW Reference Manual.
Executing Commands from the Worksheet
This next example shows how easy it is to execute a command from the Worksheetwindow. To initiate the Help command from the Worksheet, type Help followed by thecommand or tool name and press Enter. For example, if you wanted a description of thefiles command:
What to do How to do it
Show help for the Fortrancompiler, the files tool.
Type help files on a newline in the Worksheet andpress Enter.
12 Getting Started
Fortran User Guide
Help ExampleFigure 2-3
If you need general information on available Help topics, type Help and press the Enterkey.
The Commando Interface
Every MPW command has an easy-to-use Commando interface. When you choose acommand from the menus, the dialog box that you see is a part of the Commandointerface. This interface can also be accessed through a command line from theWorksheet. The Commando interface is helpful when you need to execute a commandwith multiple options and parameters. With the commando interface, you do not need toremember all of the options for MPW commands. The Commando interface allows youto build MPW commands lines directly from dialog boxes with help information readilyavailable.
The Commando dialog for any command can be invoked from the Worksheet by typingthe command name and pressing Option-Enter. The Commando interface is covered inmore detail in chapter Using the Worksheet.
Getting Started 13
Fortran User Guide
WORKING WITH SOURCE FILES
Now that you have started up MPW and looked briefly at the MPW environment, we willopen an MPW document named Hello.f90 in the FExamples folder.
What to do How to do it
Open the document using theOpen command.
Choose the File menu andselect the Open command.
Locate the Examples folderwithin the MPW folder andopen the FExamples folder.
Double-click on the Examplesfolder, then double-click onthe FExamples folder.
Open the example source fileHello.f90 in a window.
Double-click on Hello.f90.
The Hello.f90 source file will appear in a window, ready for editing.
The Hello.f90 source fileFigure 2-4
14 Getting Started
Fortran User Guide
Editing Text
We can get a feel for using the editing environment of MPW by making a small changeto the Hello.f90 source code.
What to do How to do it
Change the message text inthe Hello.f90 example tosomething different such as“Three hellos”.
Select the text, as shown inFigure 2-5, and type the newmessage (don’t type a secondset of quotations).
Selecting textFigure 2-5
Now, save the changes to your file using the Save command.
What to do How to do it
Save the changes to theHello.f90 file on disk.
Pull down the File menu andselect the Save command.
Getting Started 15
Fortran User Guide
COMPILING CODE
The Hello.f90 file is ready to be compiled by Absoft Pro Fortran. The compiler isaccessible through the Tools menu at the right end of the menu bar. When compiled andlaunched (from the Tools menu), this small Fortran 90/95 program will display a messageand then wait for the Return key to be pressed.
What to do How to do it
Display the dialog box for thecompiler.
Pull down the Tools menuand select the Compile andLaunch… command.
Select the source file,Hello.f90, to compile.
Click on the Source File(s)…button to display a fileselector for building a list offiles to compile.
Select the Hello.f90 file andpress the Add button toinclude it in the list.
Press the Done button sinceHello.f90 is the only file tocompile.
Compile the file to generatean application.
Press the Compile button. Theapplication is given thedefault name Link.Out.
16 Getting Started
Fortran User Guide
Compiling Hello.f90Figure 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 theprogram. Absoft Pro Fortran requires as little as two megabytes of memory but theSystem 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/95compiler creates an application, Link.Out that may be modified with options. See thechapter Using the Compiler for more information.
APPLICATION BASICS
Every application created by Absoft Pro Fortran has the same look and feel of all otherMacintosh applications. This environment, called the Macintosh Runtime WindowEnvironment (MRWE), makes it easy to compile and run Fortran programs created onthe Macintosh and other computers. Figure 2-7 shows the Hello.f90 application as itwill look when it is run.
Getting Started 17
Fortran User Guide
The look of a running applicationFigure 2-7
Any text in the window, such as the message displayed, may be selected and copied tothe Clipboard for pasting into other applications. Furthermore, the File menu hascommands for saving and printing text in the window.
Also, any MRWE applications are built with the Macintosh Carbon library, enablingthem to be moved to the Macintosh OS X environment and execute with the look and feelof that operating system.
To close the MRWE output window and quit from your new application, press Returntwo times. The Hello.f90 application window will close and return you to the MPWworksheet. 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 downthe File menu and select theQuit command.
18 Getting Started
Fortran User Guide
ENDING AN MPW SESSION
Any text in the Worksheet is automatically saved when you quit MPW. The text in theWorksheet window can be saved to a text file, or it can be deleted at any time byhighlighting it and pressing the Delete key.
What to do How to do it
Save the Worksheet contentsto a separate file.
Use the mouse to pull downthe File menu and select theSave a Copy command.
In the dialog, type a name forthe 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 downthe File menu and select theQuit command.
19
Fortran User Guide
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 othertext-only files (type TEXT) can be edited and manipulated with the commands explainedin this chapter.
THE MPW EDITOR
The MPW editor allows you to create and edit source files written in Fortran. Since wordprocessors embed formatting characters in a document, using a word processor to createsource files is not recommended. You can create source files in a word processor oranother editor and export them to the MPW Editor in text format, but the features of theMPW editor make this unnecessary. The editor is easy to work with and all MPW andAbsoft Fortran 90/95 commands are accessible to you at all times.
Basic editing functions in MPW are available as menu commands: most of these menufunctions are also duplicated in the MPW command language, covered in the chapterUsing the Worksheet. Since the command language is integrated throughout the MPWenvironment, 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 commandkey and the letter O ( O) 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 standardselection box will ask you to name the new file. After you have created the file, byclicking the New button, text can be entered and edited using the same editing techniquesyou use with a Macintosh-based word processor. You can cut and paste lines of textwithin the window, and move the cursor to enter text at any line.
20 Using the Editor
Fortran User Guide
Dialog for creating a new text fileFigure 3-1
Text windowFigure 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. TheEnter key tells MPW to execute a line of text as an MPW command.There is no separation of editing and command modes in MPW; itdistinguishes between the two modes only when you execute a stringof text with the Enter key.
Using the Editor 21
Fortran User Guide
2. Standard mouse techniques for highlighting text can be used whileediting a file. Clicking and dragging the cursor over multiple text linesin a window will highlight the lines. A double-click on a word willhighlight 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 andpaste text between files. Text windows have a Title Bar, a Status Panel, and vertical andhorizontal Scroll Bars. At the top/left of the scroll bar, a black rectangle called a Split Barcan be dragged to create windowpanes within one window. When a pane is created, a boxcalled the Slide box will appear at the end of the Scroll Bar. Use the Slide Box, the boxwith direction arrows, to resize the pane.
When working with multiple windows, it is important to note that MPW distinguishesbetween the active window (the frontmost window) and the target window (the secondwindow from the top). Most of the editing commands initiated from the menus will affector insert text in the active window. If you want to know which window is your activewindow, check the Window menu. In the Window menu, the active window will have acheck mark ( ) next to it. The target window, which is explained in the chapter Usingthe Worksheet, has a bullet (•) next to it. Any open window that has any unsavedchanges 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 itsCommand-key equivalent and a description of its function.
MPW also allows you to create and edit menus with the AddMenu command covered inthe chapter Using the Worksheet. Commands may be added to menus, or you can createnew menus. In fact, the Tools menu was created using the AddMenu command.
File Menu
The File menu contains commands for opening, closing, saving, andprinting files.
New…( N)Creates a new text file such as a Fortran source file. When you selectNew from the File menu, it displays a standard file dialog box forentering a file name. After entering a name for the file, a new text fileis created.
22 Using the Editor
Fortran User Guide
Open…( O)Opens an existing text file in a window for editing. This command displays a standardfile box for you to select a file to be opened. If you select a file that is already open, thewindow that contains the document is brought to the front.
Open Selection ( D)
This command is similar to Open, except that this command opens the currently selectedtext in the frontmost window. This command is handy for opening Fortran INCLUDEfiles. 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 D (the Command-keyequivalent for Open Selection).
Selection of INCLUDE file name for openingFigure 3-4
Close ( W)
This command closes the front-most window. If any unsaved changes had been made tothe text, you will be asked to save it. Since the Worksheet window cannot be closed, thiscommand will not apply to this window. When you quit from MPW, the Worksheet isautomatically saved.
Save ( S)
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 nochanges have been made in the window this command is dimmed and unavailable.
Save as…
Using the Editor 23
Fortran User Guide
Use this command to save the text of the front-most window to a different file. Astandard Save As dialog box is displayed allowing you to enter a new file name andspecify 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 stillin the front-most window, ready to be edited. Use this command to save the contents ofthe 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. Toselect or change the current printer, use the Chooser desk accessory in the Apple menu.The Print Window menu command does not show the usual dialog box: it only alerts theuser 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 Worksheetwindow (see the chapter Using the Worksheet for more information).
Quit ( Q)
Quit exits MPW and returns you to the Finder. If you have any unsaved changes in anywindow, you will be asked to save them. The Worksheet window is automatically savedwhen quitting. However, this default can be modified; customizing the Worksheet isdiscussed 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 forprogrammers are also located at the bottom of the menu.
Undo ( Z)
Use this command to undo the last change made in the front-mostwindow. Choosing Undo a second time puts the changes back.
Cut ( X)
24 Using the Editor
Fortran User Guide
This command removes the selected text in the front-most window and places it on theClipboard. Text on the Clipboard may be pasted into other windows.
Copy ( C)
The Copy command duplicates the selected text from the front-most window onto theClipboard and leaves the text in the window unchanged. Text on the Clipboard may bepasted into other windows.
Paste ( V)
This command replaces the selected text of the front-most window with the text on theClipboard. If no text is selected in the front-most window, the Clipboard text is insertedat the insertion point.
Clear
Similar to Cut, this command removes the selected text from the front-most window butdoes not place a copy on the Clipboard. The Clipboard remains unchanged.
Select All ( A)
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… ( Y)
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 isclosed. The dialog shown in Figure 3-5 shows additional settings that may be changed.
Format command dialog boxFigure 3-5
Using the Editor 25
Fortran User Guide
The Auto Indent check box automatically indents the next line with the same spacing asthe current one. Option-Return may be used at the end of a line to override theindentation.
The Show Invisibles check box displays spaces and control characters in the window. Thefollowing 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. Tochange the tab spacing, type the desired number in the Tabs text field. Be cautious whenchanging tab sizes: Fortran 90/95 source in fixed format is dependent upon columnpositions. The limit for the tab field is 100 characters. A recommended number forFortran programs is 6 characters.
Align
This command is used to horizontally align the selected text with the top line of theselection.
Shift Left and Shift Right ( [ and ])
Use these commands to horizontally shift a block of selected text by one tab stop, eitherto the left or to the right. Shift Right is ideal for indenting a block of code, such as thelines of a DO loop. By holding down the Shift key while choosing these commands, thetext 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… ( F)
This command is used to search for text, text patterns, or linenumbers.
Searching for Line Numbers
To find a line number, click on Selection Expression, type in the line number in the textbox and click on the Find button. The command will search the text beginning at thecurrent selection or insertion point.
26 Using the Editor
Fortran User Guide
Find command dialog boxFigure 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 thewindow.
Entire Word finds the string only when the characters before and after it are notword characters: a-z, A-Z, 0-9; or when characters are not underscored.
Selection Expression interprets the entered text as a regular expression and matchesthe text as a pattern.
In addition to these general options for finding text, the following options add moreflexibility and control to the text and pattern searches described above:
The Case Sensitive check box, when selected, will control whether the threesearching 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 ofthe file. The search for text stops at the end of file with forward searches; itstops at the beginning of a file for backward searches. This box is onlyavailable for Literal and Entire Word searching.
When the Wrap-Around Search check box is clicked, searching continues untilreaching the start of the search. This box is only available for Literal and EntireWord searching.
When using Selection Expression to search for text in specific patterns, different symbolscan be used as wildcard characters to match repeating or unknown characters inexpressions. This table shows the special characters that may be used in regularexpressions:
Using the Editor 27
Fortran User Guide
? Matches any single character.
≈ Matches any string of zero or more characters not includingReturn. The ≈ character is entered by typing Option-X.
[characters] Any character in the list is matched. The brackets contain thelist and must be present.
[¬characters] Any character not in the list is matched. The brackets containthe list and must be present. Type the ¬ character with Option-L.
These special characters along with the text must be between slashes (// for forwardsearches or \\ for backward searches). Figure 3-7 is an example that finds any stringbeginning with the characters “DO”.
Find dialog election expressionFigure 3-7
Find Same ( G)
This command repeats the last Find command in the front-most window. This commandhas the Command key equivalent G. To reverse the direction of the search, hold downthe Shift key while typing G. If you hold down the Shift key when you click OK, theFind command will reverse the direction as well.
Find Selection ( H)
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 andpressing H, the Command key equivalent for this command will search for the first useof the variable.
Display Selection
Ensures the current selection or insertion point is visible in the front-most window.
28 Using the Editor
Fortran User Guide
Replace… ( R)
This command is used to find and replace text. It displays a dialog box similar to that forthe Find command with a few additions.
Replace dialog boxFigure 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 thefile.
Replace Same ( T)
Use this menu command to repeat the last Replace command.
Next Error ( ≥)
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 onhow the compiler reports errors and warnings and how you can use this diagnostic outputto quickly locate problem lines in your source files.
Previous Error ( ≤)
This menu command will locate the previous source line containing an error or awarning.
Mark Menu
The Mark menu allows you to set markers within text files. A marker is asection of text that has been previously named, and is used to locate andnavigate through these sections of text. With the Mark… command, you can set markers atthe insertion point within a text window. The Mark menu also contains commands forremoving markers and finding marked sections of text in other files. As markers arecreated, they are listed as menu commands in the lower part of the Mark menu. To moveto a specific portion of text, select the corresponding marker.
Using the Editor 29
Fortran User Guide
Mark… ( M)
This command adds a new marker to the list in the Mark menu. To add a marker, eitherselect 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 boxFigure 3-9
Click the OK button. This name will appear in the lower part of the Mark menu. If youtype the name of an existing marker, a dialog box will appear and give you the chance toeither 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 namefrom the list of markers in the dialog box.
Unmark dialog boxFigure 3-10
If you click Delete, every marker that you have selected will be deleted. If you cancel, theselection is unchanged.
Browse…
The Browse command provides a fast way to find a marker in any file. When selected, adialog box appears containing a list of files and folders. As you select a file, any markersin the file will appear on the right side of the dialog. To view that marker, double-clickon the marker name. This opens the file with the marked text selected.
30 Using the Editor
Fortran User Guide
Browser dialog boxFigure 3-11
Alphabetical
List the markers in the bottom half of the Mark menu alphabetically.
Window Menu
The Window menu contains two commands for positioningwindows: Tile Windows and Stack Windows. This menu lists allopen windows in the order in which they were opened. By choosing a window from thelist, that window is brought to the front. A checkmark ( ) next to a window in the listindicates the active window (front-most window). A bullet (•) next to a window indicatesthe 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 whilechoosing this command to tile the Worksheet.
Stack Windows
This command arranges all text windows in an overlapping stacked pattern. TheWorksheet window is not affected by this command. To stack the Worksheet with thetext windows, hold the Option key.
Directory Menu
The Directory menu allows you to display or change thedefault or current directory. The default or current directorydetermines how an MPW command operates from theWorksheet.
Using the Editor 31
Fortran User Guide
When you start MPW, the default or current directory is set to the location where MPWwas launched. If you wish to invoke a command from the Worksheet that accesses a filein another directory, you must specify the entire pathname or the command will result inan error. The commands in the Directory menu are used to set the default or currentdirectory for commands executed from the MPW Worksheet.
As you change the default or current directory with the Set Directory command, each newdirectory is added as a separate menu item at the bottom of the menu to allow you toeasily 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. Tochoose a directory, select a folder and click the Directory button.
Set Directory dialog boxFigure 3-12
33
Fortran User Guide
CHAPTER 4
Using the Worksheet
This chapter will provide you with the information necessary to use the MPW Worksheetto initiate MPW commands, access on-line help in MPW, and execute programs and toolscreated by Absoft Pro Fortran. If you desire more information, refer to the MacintoshProgrammer's Workshop Manual listed in the bibliography appendix.
THE WORKSHEET WINDOW
Commands drive the MPW environment. To tell the MPW shell to perform a specificoperation, commands are issued using the menus or by typing the equivalent commandline in a window. The menu commands covered in the Using the Editor chapter make iteasy to edit source files and execute commands. These editing commands are a part ofMPW's command language set, which also includes many other useful commands forcustomizing the MPW environment, working with Fortran programs, or managing sourcefiles.
Commands can be executed in any text window; however, the MPW Worksheet providesa short-cut to executing commands in MPW. Within the Worksheet window, anycommands 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 commandsinitiated during a session.
34 Using the Worksheet
Fortran User Guide
The Worksheet windowFigure 4-1
The Worksheet window is the main work area of the MPW environment and is the firstwindow that opens when you begin an MPW session. The Worksheet window cannot beclosed and is always accessible. When you quit MPW, the Worksheet automaticallysaves its contents. You can delete the contents of the Worksheet at any time or save thetext 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 commandoutput will appear. By default, command output is sent to the window where thecommand line was executed. By invoking commands from the Worksheet, you areassured 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 sectionRouting 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.
Using the Worksheet 35
Fortran User Guide
2. Tools commands execute tools, the separate programs that are integrated within theMPW environment. Each MPW tool has a corresponding MPW command name.Sometimes the terms MPW commands and MPW tools are used interchangeably, butthere is an important difference. An MPW tool is not equivalent to a built-incommand; it is a separate program that performs more complex tasks. Some examplesof the tools in MPW are the actual Fortran 90/95 compiler, the linker, and theresource tools, Rez and DeRez.
3. Script commands execute script files. Scripts are text files containing lists ofcommands. 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 thefilename as you would any other command. Scripts will be explained later in thischapter.
4. Outside applications, such as MacDraw II or MacPaint, can also be launched withinthe MPW environment as a command. Any program can be launched from theWorksheet 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 aspecific operation. Each command can be modified by any combination ofparameters—an option or a filename. Options direct the command; they specify how thecommand should work or what the output should look like.
Every command line also has a terminator, a symbol that tells MPW to end the operationassociated with the command. The most common way to terminate a command is to usethe Return key, which adds the end of line terminator. Remember that the Return key willnot 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, thecommand can be executed by placing the insertion point within the line and pressingEnter. Command-Return is equivalent to pressing Enter. Another way to execute acommand line is to use the Status Box. A click on the Status Box is equivalent topressing the Enter key.For instance, if you wanted to show a list of files in the current directory in theWorksheet:
36 Using the Worksheet
Fortran User Guide
What to do How to do it
Execute the Files commandwhich lists all the files in thecurrent folder.
Type Files on a new line inthe Worksheet window.
Press the Enter key (not theReturn 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 theWorksheet 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 modifyor direct the command. The Files command can be used as an example. If you want tosee a list of files in your current directory and include the type, size, creator, modificationdate and creation date, you would enter the Files command with its option to list files inlong format, the letter 'l' with a dash in front (-l):
What to do How to do it
Execute the Files commandwith the option for longformat output.
Type Files -l on a new linein the Worksheet window.
Press the Enter key.
A list of options for some MPW commands is given later in this chapter. For a full list ofcommand options, refer to the MPW Command Reference Manual, available from Absoftand 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, theMPW shell will interpret these in the same manner. (In this manual, the first letter will becapitalized for consistency.) To stop command execution, type the Command key and aperiod (Command-.).
Using the Worksheet 37
Fortran User Guide
Command Terminators
A command line may be executed without a terminator. When executing more than onecommand line, a Return character usually terminates each line. Other characters may alsoterminate command lines. The table below lists the other command terminator characters.
Terminator Symbol Description
command line | command line The pipe symbol saves theresults of the first commandand uses it as input for thesecond command.
command line && commandline
The second command will beexecuted only if the firstcommand succeeds.
command line | | command line The second command will beexecuted only if the firstcommand fails.
command line ; command line The first command isexecuted, followed by thesecond command.
MPW comments can also be added to command lines using a special character. Thenumber sign (#) indicates to the shell to ignore all the text between the (#) and the Returncharacter. MPW comments can only be terminated by a Return character.
Another useful symbol is the ∂ symbol. When followed immediately by a return, thissymbol 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 looklike 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.
38 Using the Worksheet
Fortran User Guide
Accessing the Commando Interface
When entering long command lines in the Worksheet window, you might miss the easeof using the dialog boxes to select command parameters. The Commando interfaceprovides interactive mouse access to all of MPW’s features and options by invokingdialog boxes for any command. The Commando interface lets you operate moreintuitively with commands: all options are shown and help text can instantly bedisplayed. There are three ways to invoke the Commando interface for any commandentered 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 asshown in Figure 4-2.
Commando dialog for the Files commandFigure 4-2
The default button encircled with a double border in the lower-right corner of aCommando dialog executes the command, along with any options and arguments youchoose. This button is referred to as the "Do It" button. As you select multiple optionsand files in the dialog box, the equivalent command line will appear in the CommandLine Text Box.
To copy and paste the command line into a window without executing it, highlight thetext in the Command Line Text Box and choose Copy from the Edit menu. The Cancelbutton exits from the dialog without executing the command. The command line can nowbe pasted into any window.
Using the Worksheet 39
Fortran User Guide
To copy the equivalent command line to a window for later reference and execute it, holddown the Option key while clicking the "Do It" button. The complete command line iscopied to the window where the dialog box was invoked and the command is executed.
Target and Active Windows
Window menuFigure 4-3
When you enter and execute an editing command in the Worksheet window, thecommand will affect the target window, the second window from the top. If you initiatean editing command from a menu, it will affect the active window, the frontmostwindow. If you initiate an editing command from a script, it will affect the targetwindow. In the Window menu, the active window will have a check mark ( ) next to it.The target window has a bullet (•) next to it. Any open window that has any unsavedchanges 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 Filescommand used earlier. Diagnostic output consists of errors and warnings that are notexpected.
MPW commands do not need to be executed from the Worksheet, they can be executedfrom any text window. However, when a command is executed from a text window, theoutput appears in that window, not in the Worksheet. You can specifically name anoutput 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 redirectioncharacter followed by the file name that will receive the output. For example, to send thestandard output of the Files command to the file CurrentListing, enter
Files > CurrentListing
40 Using the Worksheet
Fortran User Guide
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 outputTable 4-2
A typical use for redirecting diagnostic output is to ignore harmless errors that mightoccur. 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 isempty. The error message will be discarded.
Most of the sample Fortran code included with Absoft Fortran 90/95 contains commentlines 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 windowlisted (the Worksheet) instead of sending the output to the current window(Sample.f90).
Using the Worksheet 41
Fortran User Guide
File Name Generation
Often, you will need to generate a listing of files that you have created, either to keeptrack of files, or to compile source files. MPW has special characters, that whencombined with a command, will allow you to search for and list certain patterns offilenames. Any unquoted word that contains the characters in Table 4-3 is considered afilename 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 charactersTable 4-3
When the Enter key is pressed, the unquoted word is replaced with a sorted list ofexisting filenames that match the pattern. Pattern matching is not case-sensitive. If nofilename is found matching the wildcard notation, an error is returned. For example, theFiles command can display a listing based on supplied file names.
Try using the Files command to display all Fortran source files with the .f90 extension.
What to do How to do it
Display a listing of all files endingwith the .f90 extension
Enter Files -l ≈.f90 in the Work-sheet window.
Similarly, multiple Fortran source files may be compiled at once by using a wildcardspecification 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, theymust be enclosed in quotes as in the following examples:
Files “My Disk”:source:≈F90 “read data.f90”Move “My Disk:the file” “new file”
42 Using the Worksheet
Fortran User Guide
Using MPW Variables
Environment variables, text strings that are referenced by a command, can be assigned toMPW commands. Some variables are preassigned (listed in the next section), such aspath 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 theWorksheet window.
Other environment variables may be defined and set at any time. Environment variablescan be used as a short-cut, for instance, a one-word variable can be set and used for alengthy directory pathname. The environment variable must be enclosed between braces.In the following example, the preassigned environment variable {MPW} operates as aparameter for the Directory command. When the following line is executed, the currentdirectory is set to the MPW folder.
Directory {MPW}
Variables can be expanded and used in conjunction with other character strings. Thefollowing command sets the directory to the Tools folder, located within the MPWfolder.
Directory {MPW}Tools
User-Defined Variables
The Set command creates user-defined variables. Use the UnSet command to removevariables. This example script defines a new variable, MyVariable, for referencing theTools folder in the MPW folder.
Set MyVariable {MPW}ToolsDirectory {MyVariable}
A variable’s definition is maintained until changed with another Set command orquitting MPW. By adding a Set command to the file UserStartup in the MPWdirectory, 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 beenclosed in quotes. If it is not known whether there are special characters, use quotes toinsure correct command parsing. For example, the above example should be:
Set MyVariable "{MPW}"ToolsDirectory "{MyVariable}"
Using the Worksheet 43
Fortran User Guide
Preassigned MPW Variables
The following is a useful list of environment variables that are already assigned in MPWthat can be referenced as arguments to MPW commands. It is best to not create MPWvariables 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 ofcommands typed into any window can be executed by selecting the lines and pressingEnter. This listing, called a script, can be created to automate repeated tasks, such asexecuting multiple tools at once. A group of command lines can be combined and savedas a script file.
44 Using the Worksheet
Fortran User Guide
The Directory command, the command that displays the name of the current folder inthe Worksheet window, will be used along with the Files command to demonstrate howto create and initiate a short script.
What to do How to do it
Type the current directory name, thedate, and the output of the filescommand on separate lines.
Type Directory, Date and Files onseparate lines.
Execute the commands. Using the mouse, select all lines andpress the Enter key.
This example could be saved as a script file and executed at any time, just like any otherbuilt-in command. The name assigned to the script file will be the command name. Toexecute the script, enter the script file name in the Worksheet and press Enter. Do notsave a script file with the same name as a built-in command: the built-in command willoverride execution of a script file with the same name.
Command Aliases
An alias is an alternative name for a command or a series of commands and specificparameters. Aliases are assigned with the Alias command; this command also will listalias definitions. When an alias is defined, it is only available locally until the commandor script is terminated. Aliases can be defined globally by adding them to the Startup andUserStartup Files.
For example, to define an alias for the above script:
What to do How to do it
Define an alias called Stats for aseries of commands.
Type Alias Stats "Directory;Date; Files" on a new line.
Press the Enter key.
Aliases are removed with the Unalias command. To remove an alias, enter the commandUnalias followed by the alias name. To remove all aliases, type Unalias and press theEnter key.
Startup and UserStartup are special script files that are invoked every time you begin asession in MPW. These files contain information about default environmental variablesand command aliases. It is a good idea to open a copy of these files to view an exampleof what you can do with the command language in MPW. Be careful when opening andmaking changes in the startup files: any changes will affect the startup sequence.
Using the Worksheet 45
Fortran User Guide
Structured Commands
Commands such as Files or Alias are considered to be simple commands. They consistof a single keyword, followed by zero or more options. Structured commands, on theother hand, are commands that allow you to control the order in which simple commandsare executed. An example of a structured command would be the If...Else...Endcommand.
All structured commands are built-in, and usually have more than one keyword. When astructured command is invoked, the command interpreter reads all keywords before theyare executed. A thorough listing of MPW's structured commands are given in the MPWReference Manual.
Command Execution
When a command is entered and executed with the Enter key, the MPW shell executesthe command in the following sequence:
1. Checks the command for alias substitution according to the lists ofdefined aliases.
2. Control constructs are evaluated.
3. Any variables or commands executed are replaced with theirrespective values or output.
4. The command text is divided into individual words separated byblanks.
5. Any word that contains an unquoted ? or ≈ after a variable is executedas 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 setwith special meaning to the MPW shell. When these characters are located in a commandline or a line of text, MPW will perform the action associated with the character. Aspecial character in MPW can be disabled; the character's reserved meaning can benullified by enclosing it within quotes.
Some MPW special characters have been discussed in previous sections and are listed intables 4-1, 4-2, and 4-3. Other characters, with their meanings, are discussed below.
46 Using the Worksheet
Fortran User Guide
The ∂ Character
One character that may be confusing is the ∂ character (press Option-D). Its meaning isinterpreted by the MPW shell depending on the context that it is used in. Its basicfunction is the Escape character; when used before any character, the ∂ tells the shell toquote the character. However, there are certain exceptions to this rule that are listedbelow.
∂c Take the single character c literally.
∂[Return] ∂[Return] is discarded and the MPW shell will read the command ortext 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 toa 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 (changingdirectories, opening files), or within the MPW environment. The chapter BuildingPrograms describes the commands that execute important MPW tools, such as theFortran compiler and the linker.
Although the MPW commands in this chapter are more than sufficient for using AbsoftFortran 90/95, not all of the available commands are documented, nor are all of theoptions presented for the commands that are discussed. For comprehensive descriptionsof these and other MPW commands, see the Macintosh Programmer’s Workshop Manuallisted in the bibliography appendix.
Finder commands
This list of commands brings the more important features of the Finder into the MPWenvironment, such as creating directories, working with volumes and finding source files.
Using the Worksheet 47
Fortran User Guide
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 arenecessary since the folder name contains a space. Without the quotes, twofolders named data and files would be created.
Files
Displays a list of files and folders to standard output. With no file specified, all files inthe 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 creationdate.
-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 theObjects file.
48 Using the Worksheet
Fortran User Guide
Delete
Deletes a file or a folder. If a folder is to be deleted, a dialog box will appear, askingyou to confirm the command. The -y, -n, and -c options may be used to prevent thedialog 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 intothe 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 foroverwriting 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 filealready existed.
Using the Worksheet 49
Fortran User Guide
Eject
Ejects a 3.5-inch disk after flushing and unmounting it. The volume must end with acolon (:) or be a number representing the drive number. Drive 1 is the internal drive. Ona 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 onto another task, MPW stores the most recently used tools in memory. If you decide to usethe tool again, MPW can execute the tool quicker since it is already in memory. TheFlush 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, allsubdirectories 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 afile, folder, or a certain pattern of either. The search begins with the current directory treeand moves throughout the entire volume. You can use the options below to specify whichfiles 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.
50 Using the Worksheet
Fortran User Guide
Example: whereis -v hello.f90
Searches for the file named hello.f90 with a summary of the number ofitems 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 standardoutput. 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
Using the Worksheet 51
Fortran User Guide
Choose
Use the choose command to select AppleShare volumes or printers on a network. If thevolume 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. laserwriter)-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 patternswithin 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 dateis:
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
52 Using the Worksheet
Fortran User Guide
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 lockedV invisibleM shared (can run multiple copies)I initedS systemB bundle
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 theopposite 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 allmatches, 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 Findmenu 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 notcontain a match of the pattern.
Using the Worksheet 53
Fortran User Guide
Example: Search -i /COMMON/ ≈.f90
Searches all Fortran source files ending in .f90 for the string COMMON ineither upper, lower, or mixed case.
Find
Finds a line or text pattern in the specified window and selects it. If no window isspecified, 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 thesrc (source) parameter string; output is mapped into the corresponding charactersspecified 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-Z<origFile >ucFile
Converts lowercase letters to uppercase letters in origFile and writesthe translated file to ucFile.
Sort
Sorts or merges files and prints the result on the standard output. If no input file isnamed, 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
54 Using the Worksheet
Fortran User Guide
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 writesthe 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.
Using the Worksheet 55
Fortran User Guide
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. Bothfiles 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 namedDifferences.
CompareFiles
Compare two text files and interactively view any differences. A menu named Comparewill be added to the menu bar to interactively examine the differences. The menu will bedeleted when the command is terminated.
Format: CompareFiles oldFile newFile
The Compare menu contains four items:Find next change Finds and highlights the next differencesCopy 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 fileDone 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 beopened side by side.
56 Using the Worksheet
Fortran User Guide
Equal
Compares name to targetName. If they differ the byte at which the difference occurredwill be displayed. If targetName is a file, every name must be a file as well. IftargetName is a directory and name is a file, the command will check the directory for afile 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 rightby one tab, without changing indentation. The count specifies the number of instancesthat the selection will be affected. The -l option lets you move lines by any number ofspaces to the left or right. If no window is specified, the command applies to the targetwindow (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 thatwindow. If no window is specified, the command operates on the target window (thesecond from the front).
Format: Clear [-c count] selection [window]
Option: -c count
Repeats the operation count times.
Using the Worksheet 57
Fortran User Guide
Examples: Clear §
Deletes the current selection. This acts like the Clear command in the Editmenu, 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 Copycommand 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. UseGetErrorText to access error messages for error numbers; use the Help command toaccess 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 OperatingSystem 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.
58 Using the Worksheet
Fortran User Guide
Help
Displays help information for command. If command is not specified, information isdisplayed 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 samedirectory 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 yourpersonal programming requirements. With these commands you can add special menus,create aliases for commands, or create sounds. The following list also includes theregular 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 anditemName is the name of the new menu item. With an argument missing, AddMenudisplays the command for the associated itemName, menuName, or all menus. The newmenu item can have keyboard equivalents by appending “/char” to the itemName wherechar is a keyboard character.
Format: AddMenu [menuName [itemName [command…]]]
Examples: Additional examples, including most of the ones shown below are fromthe file AddMenu in the {MPW}Example:Example folder.AddMenu Tools
Displays the commands for the compiler menu items.
Using the Worksheet 59
Fortran User Guide
The following is an example using the AddMenu command in a script. Itadds a menu command which toggles the setting of the Show Invisiblescheck 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 itemsare deleted. If no menu name or item name is specified, then all user-defined items aredeleted.
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 thedate in long form.
Format: Date [[-a | -s][-d |-t]
Options: -a Abbreviates the date. Three character abbreviations are used forthe 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 formMonday, January 29, 1990 10:45:32 AM
Date -aDisplays the date asMon, Jan 29, 1990 10:45:32 AMDate -s -dShows1/29/90
60 Using the Worksheet
Fortran User Guide
Set
Assigns the string value to the variable name. Without specifying value, the value ofname is displayed on standard output. If both name and value are not specified, a list ofall 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 usesthe variable in a Delete command.
UnSet
Removes any variable definitions. An error will not occur if a definition does not existfor name.
Format: Unset [name...]
Directory
Sets the current folder to folder when specified. When folder is not specified, thecurrent 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 quotesaround My Disk since it contains a space.
Using the Worksheet 61
Fortran User Guide
SetDirectory
Sets the current folder to folder and adds folder to the Directory menu for quickreference.
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 theDirectory menu.
Alias
An alias is a substitution for a command. Name is the alias for the command or list ofcommands, word... When name is used as a command name, word will be substituted inits place. The alias can only be used in the file where you defined it. To make an aliasavailable 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, typedir
Align
Positions all lines in the selection at the same distance from the left margin as the firstline 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 Afterb = -1.0 b = -1.0
a = sqr(b) a = sqr(b)print *,a print *,a
end end
62 Using the Worksheet
Fortran User Guide
Unalias
Removes alias definitions associated with the alias name. If no name is specified, allaliases 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 appearin 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 markerto 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 dialogboxes. 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 doesRez…
andRez (option-enter)
Using the Worksheet 63
Fortran User Guide
DumpFile
Displays the contents of the resource fork 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 youhad 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. Thedefault text will appear in the dialog box; if OK is selected, thedefault is written to standard output.
Example: Request “FileName?”
Brings up a dialog box with the prompt FileName? and a space to enterthe name of the file desired.
64 Using the Worksheet
Fortran User Guide
GetFileName
Displays a dialog box to select a given file and return a filename or pathname to standardoutput.
Format: GetFileName [-t type]...| -p | -d] [-m message]
Options: -t type
Filters the files according to the type of the file. This option is casesensitive 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 standardoutput.
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 buttonis 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 forthe user to click OK.
Quit
Using the Worksheet 65
Fortran User Guide
This command quits from the MPW shell and returns to the Finder. It is equivalent to theQuit command in the File menu.
Format: Quit
Shutdown
This command quits from MPW and shuts down the computer. With the -r option, themachine 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, asimple 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 Cletter is the note (A-G)# is an optional sharp signb is an optional flat sign
Options: duration in sixtieths of a second—the default is 15.leveldefined 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.
66 Using the Worksheet
Fortran User Guide
New
Opens a new window as the active window. If a name is not specified for the newwindow, the window will be labeled 'Untitled.' If the specified name already exists, anerror 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 appearallowing you to select a file. If name is already open, then that window becomes theactive 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 isclosed. If changes have been made, a dialog box will appear to ask you to confirm theClose 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 tobe saved before closing.
-c Answers "cancel" to any dialog boxes, causing any modifiedwindows to be left open.
Example: Close
Closes the target window, prompting the user with a dialog box if anychanges have been made.
Using the Worksheet 67
Fortran User Guide
Close -a -y
Saves and closes all open windows.
Prints text files to the selected printer. The file that is to be printed must be in the currentdirectory.
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 pages 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 pagenumber begins at 1.
Line
Finds and selects the line n in the target window. This command is generatedautomatically along with a File command by the Absoft Fortran 90/95 compiler whendisplaying errors. It may be selected and executed by pressing Enter to immediately showthe 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.
68 Using the Worksheet
Fortran User Guide
Format: Target windowname
File
Sets the filename window to be the target window. The target window is defined to bethe 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 Linecommand that selects a specific line in the target window. The File and Line commandsare 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.
Using the Worksheet 69
Fortran User Guide
MoveWindow
Moves a window to a location on the screen. The MoveWindow command moves theupper-left corner of the screen to a location which is specified by a set of coordinates, hand v. h is the horizontal coordinate, v is the vertical coordinate. Both must be integersand separated by a space on the command line. The coordinates (0, 0) are located at theleft side of the screen at the bottom of the menu bar. The target window is assumed if nowindow 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.f90Moves 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 horizontalcoordinate, v is the vertical coordinate. Both must be integers; use a space to separate thecoordinates on the command line. The default window is the target window but you canoverride 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
71
Fortran User Guide
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 anoverview of the Tools menu, this chapter explains how to compile a small number ofFortran source files into an executable application. Next, compiler error messages aredescribed as well as how to locate the point of error in the source file. The final sectionsof this chapter describe the compiler options in detail.
COMPILING PROGRAMS
Three methods of compiling programs are available: a traditional command line in theMPW Worksheet, the compiler commands in the Tools menu, and makefiles with acmtool. The command line and the compiler commands in the Tools menu are discussed inthis chapter. Makefiles and the Absoft make utility, acm, are described in the chapterBuilding Programs. All three methods allow you to compile source files quickly andeasily.
Source file names and compiler options are selected using the mouse pointer with thecompiler commands in the Tools menu and with the acm tool. Arguments to the commandline 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 yourcommands in the MPW Worksheet described in the chapter Using the Worksheet. Thecommand line version of an individual compiler can be invoked with one of thecommands: 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 thischapter.
Like other MPW commands, you can also open a commando interface for any of theindividual compilers from the MPW Worksheet:
Type f90 and press Option-Enter.
Type f90, followed by Option-semicolon (an ellipsis), and press Enter.
72 Using the Compiler
Fortran User Guide
Using the Tools Menu
The Tools menu contains commands used to access theAbsoft Pro Fortran compilers. This menu has commands forcompiling and building programs from source code, libraryfiles, and resource files. The Tools menu is divided into foursections.
The first section contains three commands for compilingsource code: Compile…, Compile & Launch…, and CompileAgain…. When Compile… or Compile & Launch… are selected,a dialog box will appear. The dialog box is part of theCommando interface, a mouse-driven interface that provides a dialog box for every tooland command in MPW. The Compile… and Compile & Launch… commands in the Toolsmenu invoke the Absoft Pro Fortran compilers for programs that have not previouslybeen compiled. Compile Again… recompiles the last file(s) selected with either theCompile… or Compile & Launch… command using the same options established at thattime.
All of these compiler commands can be used to compile a single source file or a numberof 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 newlycompiled program.
The second section of the menu contains the command for accessing the Linker… which isused for linking procedure modules together into complete applications or into librariesof modules. The operation of this tool is covered in detail in the chapter BuildingPrograms. 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 thecompiler: Fx…. The operation of this debugger is described in the chapter Using the FxDebugger. The fourth section of the Tools menu has commands for working with acm andmakefiles: the Create BuildCommands and the Build… command. These are also covered inthe 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.
Using the Compiler 73
Fortran User Guide
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 yourinstalled Absoft Pro Fortran compilers from a single interface.
Absoft Pro Fortran compiler dialog boxFigure 5-1
When the commando interface is invoked from the worksheet with the f77, f90, or acctool as described on the previous page, the initial dialog will contain controls for onlythat compiler. The options that may be selected are the same for both interfaces and aredescribed 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. Todisplay the help text, click and hold on the mouse over the field orbutton.
• Any button that contains ellipses, such as Source Files(s)…, will bringup additional dialogs.
• As options are checked in the dialog box, they will be added to theCommand Line box in the lower portion of the dialog box. Thecommand line can be pasted into any window. See the Using theWorksheet, for guidelines on pasting command lines from theCommando Dialog Boxes.
74 Using the Compiler
Fortran User Guide
Within the Compile dialog box, you can select a list of the source code files to becompiled, along with any specific options to modify the way the compiled applicationswork. When the Compile button is clicked, the source code will be compiled and linkedinto an executable program, ready to run. If any errors occur, they are listed in theWorksheet. 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 buttonclicked in the Compile Commando interface. As shown in Figure 5-2, a modified standarddialog box is displayed to select one or more source files.
Source file selection dialog boxFigure 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 directoriescan be added to the bottom list: use the drop menu with the folder (this is the directorytitle at the top of the dialog) to move to other folders. To remove a file from the bottomlist, 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 selectionsare ignored. After you choose Done or Cancel, the window will return you to the Compiledialog box.
Include Path(s) (-I)
The Compile commando dialog allows you to individually specify the path of include orheader files for each Absoft compiler you have installed and will be using. Click on theInclude Path(s) button to open the following dialog:
Using the Compiler 75
Fortran User Guide
Include and Header File Path SelectionFigure 5-3
Use the F77 Include Paths, F90 Include Paths, and ACC Include Paths buttons to selectadditional directory paths to be searched for FORTRAN 77 and Fortran 90/95 INCLUDEfiles 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 areprepended 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 isnot first found in the local directory and when it is not itself an absolute path (a full filespecification). Paths supplied with the -I option are searched before paths specified withthe F90Includes, FIncludes, and ACCIncludes MPW shell variables (see PreassignedMPW Variables in the chapter Using the Worksheet).
76 Using the Compiler
Fortran User Guide
Libraries…
Previously compiled object files and libraries of object files are added to the finalcompiler command by clicking on the Libraries… button. You can choose from thestandard libraries supplied with ProFortran or select any other library that may beavailable on your computer:
Unix Compatibility Library
The Unix library supplied routines compatible with those provided by Sun Microsystemsand other Unix based Fortran compilers. Documentation on the routines in this library isavailable in the Compatibility Libraries manual supplied with Pro Fortran. Source codeto all library routines is supplied.
None of the routines in this library are part of the ANSI FORTRAN 77 or Fortran 90/95standards 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 VAXFORTRAN. Documentation on the routines in this library is available in theCompatibility Libraries manual supplied with Pro Fortran. Source code to all libraryroutines is supplied.
None of the routines in this library are part of the ANSI FORTRAN 77 or Fortran 90/95standards 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 VisualNumerics, Inc., they comprise the widest selection of mathematical and statisticalfunctionality in the industry
Using the Compiler 77
Fortran User Guide
LAPACK Linear Algebra Library
These libraries contain the basic LAPACK and LAPACK90 libraries obtained fromwww.netlib.org. LAPACK is used for the most common problems in numerical linearalgebra including linear equations, linear least squares, eigenvalue, and singular valueproblems. LAPACK90 is the Fortran 90/95 interface for LAPACK. Source code for theselibraries is supplied with Pro Fortran.
Other Libraries…
This button opens the library selection dialog for choosing and adding any individualobject file or library of object files available on your computer.
Object and Library File SelectionFigure 5-6
The file names selected in this dialog box will usually be libraries of precompiledfunctions and subroutines, or possibly object files compiled with different languageprocessors.
Text Boxes
The three text boxes within the Compile dialog box name the executable filename, andgive 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, thedefault name, Link.Out, will be used. The executable file will be placed in the currentdirectory.
78 Using the Compiler
Fortran User Guide
Command Line Box
The command line box shows the equivalent command line for compiling the program. Ifyou select options by clicking the option buttons, the equivalent option letter will show inthe box. You can copy the command line to the Worksheet by highlighting the commandline and using Copy command in the Edit menu. If you want to copy this line to theWorksheet and execute it at the same time, hold down the Option key while clicking theCompile 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 programwill be compiled. There are three types of buttons within the dialog. Radio buttons, as inthe Output File box, provide for only one selection at a time. The push buttons, on the leftand right sides of the dialog, bring up other dialogs to select one or many compileroptions. 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. Bydefault, a stand-alone application (the MRWE Application button) is generated and linkedwith the Macintosh Runtime Window Environment (MRWE) for standard output andinput. This is a CarbonLib based application and can be run on any Macintosh operatingsystem from OS 8.6 and up, including OS X. The Output File box allows you to cancel thisdefault and make another choice, such as to generate an MPW tool, or to create an objectfile to link with other files or place in a library. Refer to the Building Programs chapterfor more information on the output file type.
Using the Compiler 79
Fortran User Guide
Main Program Box
These radio buttons are used to indicate to the linker the type of main program that willused for an executable program. This specification is necessary to insure that the requiredstartup 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 selectedoptions and source files. This is always the last button to be clicked, unless you decidenot to invoke compiler by pressing Cancel. By default, executable files generated byAbsoft Pro Fortran are placed in the current folder which may be set by using the SetDirectory command Directory menu (see the Set Directory command in the chapter Usingthe Editor and the Directory and SetDirectory commands in the chapter Using theWorksheet).
General Option Buttons
Clicking on this check box in the main Commando interface controls the creation ofsymbol tables for use with the source level debugger, Fx™. The option is specified on thecommand line as –g.
Clicking on this button in the main compiler dialog box will quickly turn on compileroptimization. This is the –O option and is the same as choosing this option in theOptimizations 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 theLAPACK libraries, special vector libraries will be linked to your program that takeadvantage of the single precision vector unit in the G4 processor.
ERRORS WHILE COMPILING
80 Using the Compiler
Fortran User Guide
When compiling a program, errors may occur, either in the source file syntax or with thecompiler options selected. All errors and warning messages for each compiler are shownin the Worksheet window in a format similar to the following:
goto 10 ^
### cf90-23 HD:MPW:AbsoftTools:f90fe: ERROR TESTSUBFile 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 theWorksheet 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 messageFigure 5-6
If you want to save a list of the errors in the Worksheet window to a text file, chooseSave a Copy from the File menu.
The Worksheet window can fill up quickly when there are many errors, especially withrepeated compilations. Although the Worksheet can store an immense amount of text, itdoes consume precious memory. The text can be cleared by choosing the Select Allcommand in the Edit menu and pressing the delete key.
GetErrorText command
The GetErrorText command displays the error messages that correspond to system errornumbers, MPW Tools or ID numbers. For example, if you type:
GetErrorText -43
MPW will list the error messages that correspond to the Macintosh Operating Systemerror -43. The GetErrorText command will not display explanations of runtime errorsassociated with the Absoft Pro Fortran compiler or errors generated by compiling Fortrancode. See the appropriate language reference manual for a summary of all compilermessages.
Using the Compiler 81
Fortran User Guide
The GetErrorText command operates by locating a file that contains the error messagesand displaying the message in the Worksheet window. By default, the GetErrorTextcommand will locate the error messages for Macintosh Operating system errors in a filenamed SysErrs.Err. MPW can also locate error message files for MPW tools and systemID numbers using special options.
Option What it does
-f filename Lists a tool's error message by accessing the errormessage file.
-i fdnbr Displays the meaning of the specified System Errorhandler ID number.
-s filename Finds the filename specified to list thecorresponding system error. The default is -sSysErrs.Err.
To locate the error messages for the system ID numbers that are reported in alert dialogboxes, 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 andMacintosh Operating System error messages are also listed.
ABSOFT FORTRAN 90/95 OPTIONS
82 Using the Compiler
Fortran User Guide
The compiler options detailed in this section give you a great deal of control over thecompilation and execution of Fortran 90/95 programs. The options fall into five generalcategories: Compiler Control, Optimizations, Compatibility, Modules paths and file, andMiscellaneous.
For quick reference, the options listed in the sections that follow are in the order in whichthey appear in the dialog boxes. Each option is listed with the corresponding optionletter(s) and a short description. When an option is checked, the same letters will appearin the Command Line box of the Compile dialog box. Options that take arguments mayoptionally have a space to separate the option from its argument. The only exceptions arethe 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 forcontrolling various aspects of compiling the Fortran programs. Click on the box next tothe option to add the option for compiling.
These options control various aspects of the compilation process such as using disk spaceinstead of memory for intermediate file storage, where include files can be found, and thedefinition of compiler directive variables. The generation of debugging information, forthe symbolic source-level debugger, Fx, is also controlled by compiler control options.
Using the Compiler 83
Fortran User Guide
Compiler control dialogFigure 5-7
Suppress warnings (-w)
Suppresses the listing of warning messages. For example, unreachable code will generatea warning message.
Frequent Command-Period checks (-N9)
An application, with the Macintosh Runtime Window Environment (MRWE), may beterminated by pressing Command-Period ( -.). The checks for -. are done at everyFortran I/O statement. The -N9 option will make the checks for -. more frequently bysetting up a vertical blank interrupt. During the checks for -, the Macintosh OperatingSystem is given the chance to execute other applications in the cooperative multitaskingenvironment 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 thecommands 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 thePowerPC branch instructions can be exceeded. In these cases, the compiler will issue awarning and the -N11 compiler option should be used to overcome the limitation. Thisoption should only be used when the compiler issues diagnostics as it will cause morecode to be generated than is usually necessary.
84 Using the Compiler
Fortran User Guide
Output Version number (-V)
The -V option will cause the f90 compiler to display its version number. This option maybe 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 firsterror that it encounters.
Allow greater than 100 errors (-dq)
Normally, the Absoft Fortran 90/95 compiler will stop if more than 100 errors areencountered. This many errors usually indicate a problem with the source file itself or theinability to locate an INCLUDE file. If you want the compiler to continue in thiscircumstance, select the -dq option.
Default Recursion (-eR)
If you select the -eR option, all FUNCTIONs and SUBROUTINEs are given the RECURSIVEattribute. Normally, if the compiler detects a recursive invocation of a procedure notexplicitly given the RECURSIVE attribute, a diagnostic message will be issued. The -eRoption 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 compilationtime. If system memory is limited, the compiler can be instructed to create these files ondisk by specifying the -F option. The names of intermediate files are generated by theMacintosh and begin with "tmp". Since these files are only useful to the compiler, theywill be removed automatically at the end of the compilation process. However, if thecompiler is unable to delete them, they may be removed manually by dragging their iconsto the trash can.
Warn of non-standard usage (-en)
Use of the -en option will cause the compiler to issue a warning whenever the sourcecode contains an extension to the Fortran 90/95 standard. This option is useful fordeveloping code which must be portable to other environments.
Using the Compiler 85
Fortran User Guide
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, comments1 errors, warnings, cautions, notes2 errors, warnings, cautions3 errors, warnings4 errors
The default level is -z3; the compiler will issue error and warning diagnostics, but notcautions, 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 messagenumber. This option is useful if the source code generates a large number of messageswith 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 statisticsfor analysis of runtime bottlenecks. Profiling is introduced at the end of the chapterMacintosh Programming in this manual and described in detail in the chapter Using theFx Debugger.
Generate procedure trace (-N80)
Specifying the –N80 option will cause the compiler to generate code to write the name ofthe currently executing procedure to standard out. This option is useful for tracingprogram execution and quickly isolating execution problems.
OPTIMIZATIONS…
This button displays a dialog of compile time optimizations that generates an applicationwith 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 ofstatements or entire programs. There are pros and cons when choosing optimizations; theapplication will execute much faster after compilation but the compilation speed itselfwill be slow. Some of the optimizations described below will benefit almost any Fortrancode, while others should only be applied to specific situations.
86 Using the Compiler
Fortran User Guide
Optimizations (-O)
The -O option will cause most code to run faster. It includes common subexpressionelimination, loop invariant removal, and strength reduction. This option is selected on thefirst page of Compile commando dialog.
Optimizations dialogFigure 5-8
COMPATIBILITY…
This button displays a dialog box of options for compiling Fortran programs. Theseoptions allow Absoft Fortran 90/95 to accept older or variant extensions of Fortransource code from other computers such as mainframes. Many of these can be used forincreased compatibility with Fortran compilers on various mainframe computers.
Compatibility options dialog boxFigure 5-9
Using the Compiler 87
Fortran User Guide
Source Formats
For compatibility with other Fortran environments and to provide more flexibility, thecompiler can be directed to accept source code that has been written in a number ofdifferent 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 forthe Fortran 90/95 Free Source Form. This is the default for file names with an extensionof “.f90”.
Fixed-Form (-f fixed)
The -f fixed option instructs the compiler to accept source code written in the format forthe Fortran 90/95 Fixed Source Form which is the same as the standard FORTRAN 77source form.
Fixed line length (-W nn)
Use the -W option to set the line length of source statements accepted by the compiler inFixed-Form source format. The default value of nn is 72. The other legal values for nnare 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 typesdefault 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 doubleprecision equivalents (KIND=8). This option does not affect variables which appear intype 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 andconstants 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 withD exponents will be converted to the complex kind in which each part has the default realkind.
Static storage (-s)
The -s options is used to allocate local variables statically, even if SAVE was not specifiedas an attribute. In this way, they will retain their definition status on repeated referencesto the procedure that declared them. Two types of variables are not allocated to staticstorage: variables allocated in an ALLOCATE statement and local variables in recursiveprocedures.
88 Using the Compiler
Fortran User Guide
Disable compiler directive (-xdirective)
The -x option is used to disable compiler directive in the source file. directive may be anyof the following:
NAMEFIXEDFREESTATIC
See the section Absoft Fortran 90/95 Compiler Directives for more information onusing 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 orfour bytes (KIND=4). The –i2 option can be used to change this default length to sixteenbits or two bytes (KIND=2). However, an explicit length specification in a type declarationstatement 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 orfour bytes (KIND=4). The –i8 option can be used to change the default INTEGER size to 64bits or 8 bytes (KIND=8). However, an explicit length specification in a type declarationstatement 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 establishedfrom the DO parameter list, is zero. The -ej option will cause all DO loops to be executed atleast once, regardless of the initial value of the iteration count.
Using the Compiler 89
Fortran User Guide
The Miscellaneous button in the Compatibility… dialog box will show the following dialogwhen clicked:
Miscellaneous Compatibility options dialog boxFigure 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 evenextremely large programs. However, under certain circumstances, this value may beexceeded and the compiler will issue a diagnostic indicating that the value should beincreased.
The default value can be increased by powers of ten by specifying the -T nn, where nn isa positive integer constant. When this option is specified, the number of handles will be100000x10nn bytes.
Temporary string size (-t nn)
In certain cases the compiler is unable to determine the amount of temporary string spacethat string operations will require. The compiler will assume that the operation inquestion will require 1024 bytes of temporary string space. This default value can beincreased by powers of ten by specifying the -t nn, where nn is a positive integerconstant. When this option is specified, the default temporary string size will be1024x10nn bytes.
90 Using the Compiler
Fortran User Guide
Module File Path(s) (-p)
Click the Module File Path(s) button to specify directory paths that will prepended to filescontaining module definitions (see Module File(s) below):
Module File PathsFigure 5-11
Module File(s) (-p)
MODULE definitions can be used in multiple files in one of two ways. Either place them inINLCUDE files and include them in files that use them or place them in a source file andcompile to create pre-compiled module definition files. Precompiled MODULE files aredistinguished with the .mod extension given to them by the compiler when they arecreated. The advantage of pre-compiled module files is the increased speed ofcompilation of files that use them.
Using the Compiler 91
Fortran User Guide
Click the Module Files(s) button on the F90 dialog to specify which pre-compiled MODULEfiles you want the compiler to use:
Module FilesFigure 5-12
MISCELLANEOUS…
This button displays a dialog box of various Fortran 90/95 options for controlling therepresentation of externally visible symbols and additional debugging capabilities. Theseoptions allow Absoft Fortran 90/95 to accept variant extensions of Fortran 90/95 sourcecode from other computers such as mainframes. Many of these can be used for increasedcompatibility with programs written in other programming languages.
92 Using the Compiler
Fortran User Guide
Escape Sequences in Strings (-YCSLASH=1)
If the -YCSLASH=1 option is turned on, the compiler will transform the following escapesequences 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 fieldcomponent dereference operator. The default is to allow both ‘%’ (percent), which is theFortran 90/95 standard, and a period which is typically used with DEC style RECORDdeclarations. The use of a period may cause certain Fortran 90/95 conforming programsto be mis-interpreted (a period is used to delineate user defined operators and someintrinsic operators). The default is -YNDFP=0. This switch implements Fortran 90/95standard 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 areemitted. The default (-YEXT_NAMES=UCS) is to emit COMMON block names entirely inupper case. Set this option to LCS to emit names entirely in lower case. Use ASIS to emitthe 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 externalrepresentation 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 externalrepresentation of COMMON block names.
Using the Compiler 93
Fortran User Guide
Check Array Boundaries (-Rb)
When the –Rb compiler option is turned on, code will be generated to check that arrayindexes 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 bedisplayed with all run time error messages.
Check Array Conformance (-Rc)
The –Rc compiler option is used to check array conformance. When array shapes are notknown at compile time and where they must conform, runtime checks are created toinsure that two arrays have the same shape.
Check Substrings (-Rs)
When the –Rs compiler option is turned on, code will be generated to check thatcharacter substring expressions do not specify a character index outside of the scope ofthe character variable or character array element.
Check Pointers (-Rp)
Use –Rp compiler option is used to generate additional program code to insure thatFortran 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 visiblesymbols, such as FUNCTION and SUBROUTINE names, are emitted. By default, names areemitted entirely in upper case. Set this option to LCS to emit names entirely in lowercase. Set this option to ASIS to force external names to emitted exactly as they appear inthe source program. This option controls how external names will appear to other objectfiles.
External Symbol Suffix (-YEXT_SFX=string)
The -YEXT_SFX option can be used to append a user specified string to the externalrepresentation of external procedure names.
Other F90/95 Options
The following options are not available with the graphical interface to the compiler butmay used with the command line interface or the make facility (See the chapter, BuildingPrograms).
94 Using the Compiler
Fortran User Guide
-YDEALLOC= {MINE | ALL | CACHE})
This option is used to control the underlying runtime memory management associatedwith the Fortran 95 ALLOCATE and DEALLOCATE statements. By default the runtime cachesmemory which has been deallocated (CACHE). Specifying MINE will cause all userallocated memory to be returned via a call to free(2) when a call to DEALLOCATE isexecuted. Specifying ALL will cause all user allocated memory to be returned via a call tofree(2) and return any compiler allocated memory that has been cached. The tradeoff isminimizing memory use (ALL/MIME) versus speed of execution (CACHE).
YPEI={0|1}
Pointers Equivalent to Integers. This option controls whether or not the compiler willallow or accept a CRI style pointer to be equivalent to an integer argument. By defaultthe Absoft Fortran 90/95 compiler allows this. Even with this relaxed error checking thecompiler will correctly choose the right interface for the following example:
interface generic subroutine specific1(i)
integer i end subroutine specific1 subroutine specific2(p)
integer ipointer (p,i)
end subroutine specific2end interfacecall generic(i)call generic(loc(i))end
Regardless of the switch setting, this example will compile and the executable generatedwill 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 beperformed by the compiler. They are not Fortran 90/95 statements. If you specify acompiler directive while running on a system that does not support that particulardirective, the compiler ignores the directive and continues with compilation.
A compiler directive line begins with the characters CDIR$ or !DIR$. How you specifycompiler directives depends on the source form you are using.
If you are using fixed source form, indicate a compiler directive line by placing thecharacters CDIR$ or !DIR$ in columns 1 through 5. If the compiler encounters a nonblankcharacter 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
Using the Compiler 95
Fortran User Guide
default 72 column width, characters beyond column 72 are ignored. If you have specified80 column lines, characters beyond column 80 are ignored.
If you are using free source form, indicate a compiler directive line by placing thecharacters !DIR$ followed by a space, and then one or more compiler directives. If theposition following the !DIR$ contains a character other than a blank, tab, or newlinecharacter, 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 directivewith a comma.
NAME Directive
The NAME directive allows you to specify a case-sensitive external name in a Fortranprogram. You can use this directive, for example, when writing calls to C routines. Thecase-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 Fortranprogram 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 freesource form. The FREE directive may appear anywhere within your source code. Theformat of the FREE directive is:
!DIR$ FREE
You can change source form within an INCLUDE file. After the INCLUDE file has beenprocessed, the source form reverts back to the source form that was being used prior toprocessing the INCLUDE file.
FIXED Directive
The FIXED directive specifies that the source code in the program unit is written in thefixed 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 beenprocessed, the source form reverts back to the source form that was being used prior toprocessing the INCLUDE file.
96 Using the Compiler
Fortran User Guide
STACK Directive
The STACK directive causes the default storage allocation to be the stack in the programunit that contains the directive. This directive overrides the -s command line option inspecific 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 thecompilation and execution of FORTRAN programs. The options fall into three generalcategories: Compiler Control, Optimizations, and Compatibility.
For quick reference, the options listed in the sections that follow are in the order in whichthey appear in the dialog boxes. Each option is listed with the corresponding optionletter(s) and a short description. When an option is checked, the same letters will appearin 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 onlyexception are the N options: they do not have a space between the option and theargument (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 theLAPACK libraries, special vector libraries will be linked to your program that takeadvantage of the single precision vector unit in the G4 processor.
Using the Compiler 97
Fortran User Guide
COMPILER CONTROL...
When clicked, this button in the Compile dialog box displays a dialog of options forcontrolling various aspects of compiling the FORTRAN programs. Click on the box nextto the option to add the option for compiling.
These options control various aspects of the compilation process such as using disk spaceinstead of memory for intermediate file storage and the definition of compiler directivevariables. The generation of debugging information, for the symbolic source-leveldebugger, Fx, is also controlled by compiler control options.
Compiler control dialogFigure 5-13
Suppress warnings (-w)
Suppresses the listing of warning messages. For example, unreachable code or a missinglabel on a FORMAT statement generate warning messages. Compile time diagnosticmessages are divided into two categories: errors and warnings. Error messages indicatethat the compiler was unable to generate an output file. Warning messages indicate thatsome syntactic element was not appropriate, but the compiler was able to produce anoutput file.
Suppress alignment warnings (-A)
The compiler normally will issue a warning message if a variable is aligned on aboundary which does not match its size. Misaligned storage locations slow down memoryaccess 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.
98 Using the Compiler
Fortran User Guide
Use 32-bit branches (-N11)
In certain types of unusually large program units, the 16-bit addressing capability of thePowerPC branch instructions can be exceeded. In these cases, the compiler will issue awarning and the -N11 compiler option should be used to overcome the limitation. Thisoption should only be used when the compiler issues diagnostics as it will cause morecode 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 ofthe currently executing procedure to standard out. This option is useful for tracingprogram execution and quickly isolating execution problems.
Generate profiler information (-p)
Specifying the -p option will place profile information into a compiled program. Fx, thesymbolic debugger, can then be used to gather procedure entry and timing statistics foranalysis of runtime bottlenecks. Profiling is introduced at the end of the chapterMacintosh Programming in this manual and described in detail in the chapter Using theFx Debugger.
Check array boundaries (-C)
When the -C compiler option is turned on, code will be generated to check that arrayindexes 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, filenames 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 symbolinformation for Fx. Fx is supplied with the Absoft Pro Fortran development system.Debugging Fortran applications is introduced at the end of the chapter MacintoshProgramming in the section titled Debugging and completely described in the chapterUsing the Fx Debugger. This option implicitly enables the -m option for suppressingdelayed stores.
Min Debug with Fx (-gmin)
Specifying the -gmin option on the command line will cause the compiler to generate linenumber information only for Fx – variables cannot be examined or modified. However,full optimization can used with this option and program execution can be profiled withFx. Fx is supplied with the Absoft Pro Fortran development system. Debugging Fortranapplications is introduced at the end of the chapter Macintosh Programming in thesection titled Debugging and completely described in the chapter Using the FxDebugger.
Using the Compiler 99
Fortran User Guide
Info for unused structures (-N111)
Normally, the compiler does not place information in the debugger symbol tables forstructures which are only declared, but never have storage associated with them. Thiskeeps the symbol tables to a manageable size when include files are used to makestructure declarations. The -N111 option can be used to force the compiler to placeinformation in the debugger symbol tables for all structures whether they have associatedstorage 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 aregister to memory as long as possible. The result of doing this may make the datainaccessible to other tasks. If it is important that data be written to memory as soon as itchanges value, the use of the -m compiler option will force the compiler not to delayregister 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 thecompiler unless the -x compiler option is selected. This option allows a restricted form ofconditional compilation designed primarily as a means for easily removing debuggingcode from the final program. When the -x option is selected, any occurrence of an X or aD in column one is replaced by a blank character. The only source formats for whichconditional compilation is valid are standard FORTRAN 77, VAX Tab-Format, and wideformat. The compiler also incorporates a complete set of statements for conditionalcompilation which are described in the Conditional Compilation Statements section ofthe 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 evenextremely large programs. However, under certain circumstances, this value may beexceeded and the compiler will issue a diagnostic indicating that the value should beincreased.
100 Using the Compiler
Fortran User Guide
The Miscellaneous button in the Compiler Control… dialog box will show the followingdialog when clicked:
Miscellaneous Compiler Control options dialog boxFigure 5-14
Output
The normal output of the compiler is directed to standard output (the Worksheetwindow). This pop-up menu can be used to redirect this normal progress output of thecompiler to a different window or to a file. (See ROUTING COMMAND OUTPUTin 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 (theWorksheet window) as it compiles an application. Enabling the -q option will suppressany messages printed to standard output. Errors will still be printed to standarddiagnostic, however.
Show progress (-v)
Enabling the -v option will cause the f77 shell script, described earlier in this chapter, todisplay the commands it is sending to the compiler and linker.
Using the Compiler 101
Fortran User Guide
Frequent Command-Period checks (-N9)
An application, with the Macintosh Runtime Window Environment (MRWE), may beterminated by pressing Command-Period ( -.). The checks for -. are done at everyFORTRAN I/O statement listed in the Input/Output and Format Specifications chapterof the FORTRAN 77 Language Reference Manual. The -N9 option will make the checksfor -. more frequently by setting up a vertical blank interrupt. During the checks for -.,the Macintosh Operating System is given the chance to execute other applications in thecooperative multitasking environment of the Macintosh. Using this option will slowprogram execution slightly, but the application will remain friendly during longcomputations 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 compilationtime. If system memory is limited, the compiler can be instructed to create these files ondisk by specifying the -F option. The names of intermediate files are generated by theMacintosh and begin with "tmp". Since these files are only useful to the compiler, theywill be removed automatically at the end of the compilation process. However, if thecompiler is unable to delete them, they may be removed manually by dragging their iconsto the trash can.
Define Compiler directives (-Dname[=value])
Use this scrollable text box to enter the names and optional values of conditionalcompilation 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 thevalue of 1. Conditional compilation is described in the Conditional CompilationStatements section in the FORTRAN 77 Program chapter of the FORTRAN 77Language Reference Manual.
Generate object files (-c)
The -c option causes the compiler to suppress creation of an executable file and leaveobject 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 samename as the FORTRAN source file with the characters “.o” appended. In the mainFortran 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 bya successful and complete compilation. Specifying the -o name option, where name is a
102 Using the Compiler
Fortran User Guide
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 filename.
OPTIMIZATIONS…
This button displays a dialog of compile time optimizations that generates an applicationwith code that executes quickly. Absoft Fortran 77 is a globally optimizing compiler, sovarious optimizers can be turned on which affect single statements, groups of statementsor entire programs. There are pros and cons when choosing optimizations; the applicationwill 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 dialogFigure 5-15
You may want to ignore optimizations during program development or for compilationsof FORTRAN source code ported to the Macintosh to save time. When a FORTRANprogram is executing correctly and has been debugged, turn on optimizations forimproved run-time performance. Most programs achieve their largest initial performancegain when Basic optimizations is selected. In general, all optimizations should be selectedcarefully.
Basic optimizations (-O)
The -O option is a group of basic optimizations which will cause most code to run fasterwithout the expense of application size or memory usage. These include commonsubexpression elimination, loop invariant removal, and strength reduction.
DATA treated as constants (-N5)
The -N5 compiler option enables the optimizer to propagate as constants those variablesinitialized in DATA statements which are not redefined. For example:
Using the Compiler 103
Fortran User Guide
Original code: Becomes:SUBROUTINE DIVIDE(A)INTEGER A(50),B,C
DATA B,C/100,10/
DO I=1,50A(I) = A(I)/B-I*C
END DORETURNEND
SUBROUTINE DIVIDE(A)INTEGER A(50),B,C
DATA B,C/100,10/
DO I=1,50A(I) = A(I)/100-I*10
END DORETURNEND
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 whereverpossible. 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 loopsin your source code. Loops may be unrolled by any power of two. Generally it isbeneficial to unroll loops which execute a large number of iterations, while the benefit issmall for loops which iterate only a few times. Due to this, only innermost loops areconsidered for unrolling. The -h nn option will cause the compiler to unroll yourinnermost loops nn times, where nn is any power of two. The -H nn option will cause thecompiler to consider loops containing nn or fewer statements for unrolling. When the -Ooption is used, the default is to only consider loops of a single line and unroll them fourtimes. Using the -U option is equivalent to using -h 2 -H 10, causing innermost loops often or fewer lines to be unrolled twice. Loop unrolling will provide a speed increase inmost cases, but will make your application larger and it will require more memory tocompile. Consider the following example:
104 Using the Compiler
Fortran User Guide
Original code: Becomes:SUBROUTINE SUB(A,N,X)INTEGER A(100)
DO i=1,NA(i) = X*A(i)
END DORETURNEND
SUBROUTINE SUB(A,N,X)INTEGER A(100)
DO i=1,MOD(N,4)A(i) = X*A(i)
END DODO i=4,N-(MOD(N,4)),4
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 DORETURNEND
At least three comparisons and three branch instructions are saved each time the secondloop is executed. Note that if your code contains extended range DO loops, unrolling loopswill invalidate your program.
COMPATIBILITY…
This button displays a dialog box of options for compiling FORTRAN programs. Theseoptions allow Absoft Fortran 77 to accept older or variant extensions of FORTRANsource code from other computers such as mainframes. Many of these can be used forincreased compatibility with FORTRAN compilers on various mainframe computers.
Compatibility options dialog boxFigure 5-16
Using the Compiler 105
Fortran User Guide
Folding to lower case (-f)
The -f option will force all symbolic names to be folded to lower case. By default, thecompiler considers upper and lowercase characters to be unique, an extension toFORTRAN 77. If you do not require case sensitivity for your compilations or specificallyrequire that the compiler not distinguish between case, as in FORTRAN 77, use thisoption. This option should be used for compatibility with VAX and other FORTRANenvironments.
Static storage (-s)
In FORTRAN 66, all storage was static. If you called a subroutine, defined localvariables, and returned, the variables would retain their values the next time you calledthe subroutine. FORTRAN 77 establishes both static and dynamic storage. Storage localto an external procedure is dynamic and will become undefined with the execution of aRETURN statement. The SAVE statement is normally used to prevent this, but the -scompiler option will force all program storage to be treated as static and initialized tozero. The -N1 compiler option causes the definition of variables initialized in DATAstatements to be maintained after the execution of a RETURN or END statement. This optionshould 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 allappropriate OPEN statements. See the Input/Output and Format Specifications chapterof the FORTRAN 77 Language Reference Manual for more information about theBLOCK=-1 specifier. This option should be used for compatibility with VAX and otherFORTRAN environments.
RECL Defines 32-bit words (-N51)
If the -N51 compiler option is used, the “RECL” specifier will be interpreted as the numberof 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 forcompatibility with VAX and other FORTRAN environments.
Folding to upper case (-N109)
By default, the compiler considers upper and lowercase characters to be unique, anextension to FORTRAN 77. If you do not require case sensitivity for your compilationsor specifically require that the compiler not distinguish between case, as in FORTRAN77, including the -N109 option on the compiler invocation command line will force allsymbolic names to be folded to upper case.
106 Using the Compiler
Fortran User Guide
One-trip DO loops (-d)
FORTRAN 66 did not specify the execution path if the iteration count of a DO loop, asestablished from the DO parameter list, was zero. Many processors would execute thisloop once, testing the iteration count at the bottom of the loop. FORTRAN 77 requiresthat such a DO loop not be executed. The -d option will cause all DO loops to be executedat 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 executionof a program, all sixteen and eight bit values are extended to thirty-two bits before anyoperation 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 compatibilitywith other implementations of FORTRAN, the -N102 option can be used to direct thecompiler to zero extend these variables when they are loaded, making them essentiallyunsigned 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 sourcecode contains an extension to the ANSI FORTRAN 77 standard (American NationalStandard Programming Language FORTRAN, X3.9-1978). This option is useful fordeveloping 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 programas though they where declared with the GLOBAL statement. The GLOBAL statement allowsvariables declared in shared libraries to be accessed by other program units.
Using the Compiler 107
Fortran User Guide
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 ofdifferent formats. The default setting is to accept only ANSI standard FORTRAN sourcecode format. See the FORTRAN 77 Program chapter of the FORTRAN 77 LanguageReference 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 forthe 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 specifiedby IBM VS Free Form.
VAX Tab-Format (-V)
Use of the -V option causes the compiler to accept source code in the form specified byVAX Tab Format.
Wide format (-W)
Use of the -W option causes the compiler to accept statements which extend beyondcolumn 72 up to column 132.
Set Big-Endian (-N26)
Use this option to force the compiler to consider the byte ordering of all unformatted filesto be big-endian by default . The CONVERT specifier in the OPEN statement may be used tooverride this setting for individual files.
Set Little-Endian (-N27)
Use this option to force the compiler to consider the byte ordering of all unformatted filesto be little-endian by default . The CONVERT specifier in the OPEN statement may be usedto 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 globalnames for COMMON blocks. The default is to prepend the characters “_C” to the COMMONblock name. This option cau1se the compiler to append a single underscore (_) instead.This option is intended primarily for compilers installed on Linux-based systems.
108 Using the Compiler
Fortran User Guide
The Miscellaneous button in the Compatibility… dialog box will show the following dialogwhen clicked:
Miscellaneous Compatibility options dialog boxFigure 5-17
Evaluate left-to-right (-N20)
When two or more operators of equal precedence appear consecutively in an arithmeticexpression, 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 efficientmethod or not.
Don’t generate FMA instructions (-Q51)
Use of the -Q51 option will cause the compiler not to use floating-point multiply-add typeof instructions. Since there is no rounding performed between the multiplication andaddition during the execution of these instructions, numeric results will vary dependingon 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 Cenvironments.
Using the Compiler 109
Fortran User Guide
Sign extend BYTE() & WORD() (-N7)
The -N7 compiler option causes the compiler to extend the sign of a value returned fromthe intrinsic functions BYTE and WORD. This option has no effect on the memory assign-ment statements described in the Expressions and Assignments chapter of theFORTRAN 77 Language Reference Manual.
DATA variables are static (-N1)
The -N1 compiler option causes all variables initialized with DATA statements to bestored as static variables.
Promote REAL and COMPLEX (-N113)
Without an explicit length declaration, single precision REAL and COMPLEX data typesdefault 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: DOUBLEPRECISION and DOUBLE COMPLEX. This option does not affect variables whichappear 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 markedwith a ‘\’ embedded in character constants. For example ‘\n’ will be transformed into anewline character for your system. Refer to the FORTRAN 77 Program chapterFORTRAN 77 Language Reference Manual for more information on the escapesequences 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 ablock CASE structure when a match is not found. The -N4 causes control of execution tobe transferred to the statement following the END SELECT statement when a CASEDEFAULT statement is not present and no match is found, preventing such a run-timeerror.
Allows UNIT= without FMT= (-N16)
If the -N16 compiler option is used, the format specifier FMT= may be omitted in an I/Ostatement 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 mayinvalidate your code if the same COMMON block is defined differently in different programunits.
110 Using the Compiler
Fortran User Guide
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 toreverse 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 basedMacintosh systems, to inform the compiler of a non-standard function interface, typicallya toolbox call. The PowerPC toolbox interface conforms to an ABI (Application BinaryInterface) which is well defined and consistent between programming languages. Hence,the PASCAL keyword is no longer required. The default behavior of the compiler is toaccept the PASCAL keyword, but to ignore it. The -N21 option can be used to cause thecompiler 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 FUNCTIONnames with a trailing underscore. This option can be used to avoid name conflicts withthe 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 spacethat string operations will require. This undetermined length occurs when the REPEATfunction is used or when a CHARACTER*(*) variable is declared in a subroutine orfunction. In these cases, the compiler will assume that the operation in question willrequire 1024 bytes of temporary string space. Specifying the -t nn option, where nn is apositive integer constant, can change this default value. When this option is specified, thedefault temporary string size will be nn bytes.
STRUCTURE Alignment
Normally, the fields in a STRUCTURE are aligned based on the standard for C. This maycause spaces to be left between structure elements and space to be added to the end of astructure. 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 theconditional compilation directives $PACK and $PACKOFF to control the packing ofindividual structures (see the section Conditional Compilation Directives in theFORTRAN 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 willoccur between fields. The use of this option may cause misaligned storage locations.
Using the Compiler 111
Fortran User Guide
Align STRUCTURE fields to 2 byte boundaries (-N57)
The –N57 option will force structure fields to be aligned to 2-byte boundaries. Fieldsbeginning at odd addresses will be aligned to the next even address. The use of thisoption 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 notbeginning at a modulo 4 address will be aligned to the next 4-byte boundary. The use ofthis option may cause misaligned storage locations for fields greater than 4 bytes inlength..
Align STRUCTURE fields to 8 byte boundaries (-N59)
The –N59 option will force structure fields to be aligned to 8-byte boundaries. Fields notbeginning 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 thecommand 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 anerror diagnostic whenever it encounters an undeclared variable. If you specify the –N114option, 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 –Woption). By default, the compiler considers only the characters actually present in thesource file. This option is useful when porting certain legacy programs that depend on thecompiler reading source records as card images.
Debug with Fx (-g)
Specifying the -g option on the command line will cause the compiler to generate symbolinformation 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 forCOMMON blocks. The default is to prepend the characters “_C” to the COMMON block nameso 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 insource. See also the -N25 option above.
112 Using the Compiler
Fortran User Guide
ABSOFT C/C++ OPTIONS
The compiler options detailed in this section give you a great deal of control over thecompilation and execution of C and C++ programs. The options fall into three generalcategories: Compiler Control, Compatibility, and Preprocessor.
ACC OptionsFigure 5-18
For quick reference, the options listed in the sections that follow are in the order in whichthey appear in the dialog boxes. Each option is listed with the corresponding optionletter(s) and a short description. When an option is checked, the same letters will appearin the Command Line box of the ACC dialog box. Options that take arguments must have aspace 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 subexpressionelimination, loop invariant removal, and strength reduction.
Source Formats
The radio buttons in the Source Formats box are used to specify the C/C++ dialectaccepted by the compiler.
ARM C++ (-Tp)
C++ source conforming to the Annotated C++ Reference Manual is specified with -Tpoption.
Using the Compiler 113
Fortran User Guide
Draft Std C++ (-std)
Enabling the -std option allows you to use the namespaces and runtime type informationfeatures 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 Cprogramming 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 olderstyle 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 forcontrolling various aspects of compiling the C/C++ programs. Click on the box next tothe option to add the option for compiling.
These options control various aspects of the compilation process such as the level ofdiagnostic warning desired, the use of memory or disk for temporary files, and whetherfunction inlining is allowed.
Compiler control dialog
Use long branches (-N18)
In certain types of unusually large program units, the 16-bit addressing capability ofPowerPC branch instructions can be exceeded. In these cases, the compiler will issue awarning and the -N18 compiler option should be used to overcome the limitation. This
114 Using the Compiler
Fortran User Guide
option should only be used when the compiler issues diagnostics as it will cause morecode 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 betweenpasses. 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 ofintermediate files are generated by the Macintosh and begin with "tmp". Since these filesare only useful to the compiler, they will be removed automatically at the end of thecompilation process.
Profiler Information (-p)
Specifying the -p option will place profile information into a compiled program. Fx, thesymbolic debugger, can then be used to gather procedure entry and timing statistucs foranalysis of runtime bottlenecks. Profiling is described in detail in the chapter Using theFx Debugger.
Procedure Trace (-N124)
Specifying the -N124 option will cause the compiler to generate code to write the name ofthe currently executing procedure to standard out. This option is useful for tracingprogram 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/throwconstructs in your program. All functions that are called directly or indirectly from a tryblock must be compiled with the -except on option. Only specify this option when you areactually 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. TheAbsoft 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 isallowed on the assumption that you know what you are doing
informational the element is legal but may be the cause of a subtle bug
Using the Compiler 115
Fortran User Guide
anachronism currently allowed construction which may not be supported in afuture release
template show the point of instantiation of a template function when thatinstantiation caused an error
Suppress all warnings (-w31)
Checking this box suppresses the listing of all diagnostic warning messages. Variouslevels of warnings may be suppressed by checking the individual warning boxes asdiscussed below.
Suppress warnings (-w16)
Checking this box suppresses the listing of most warning messages. The only diagnosticwarnings still reported are informational and anachronisms.
Suppress informationals (-w8)
This check box controls the listing of informational warning messages such as using amember name in a derived class that was defined in the base class, referencing a functionwhich 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 atemplate function.
Treat anachronisms as errors (-wp)
This check box causes the usage of C++ anachronisms to be treated as errors. This optionshould always be used when developing new code to avoid the use of deprecatedfeatures.
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 compileraborts. Setting a reasonable number, such as 20, prevents the compiler from issuinghundreds of meaningless error messages when a brace or semi-colon is missing.
116 Using the Compiler
Fortran User Guide
COMPATIBILITY…
This button displays a dialog box of options for compiling C/C++ programs. Theseoptions are designed to provide provide compatibility with various commonimplementations of and extensions to the C programming language.
Compatibility options dialog boxFigure 5-20
Suppress Apple extensions (-appleext off)
By default, the compiler accepts the following Apple extensions to the C programminglanguage:
• 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 PowerPCalignment—use the -align mac68k to override the alignment.
Using the Compiler 117
Fortran User Guide
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 dialogbox will be presented:
Munch options dialog boxFigure 5-21
Set initialization prefix (-init prefix)
Each object module created by the compiler which contains global data items or objectsthat require static contruction must call an initialization routine. The -init prefix optionallows you to specify the prefix given to this routine in case you are using a linker otherthan the one supplied by Absoft.
Set termination prefix (-term prefix)
Each object module created by the compiler which contains global data items or objectsthat require static destruction must call a termination routine. The -term prefix optionallows you to specify the prefix given to this routine in case you are using a linker otherthan the one supplied by Absoft.
118 Using the Compiler
Fortran User Guide
PREPROCESSOR…
This button displays a dialog box of options for controlling the preprocessor stage of theC and C++ compilation process.
Preprocessor options dialog boxFigure 5-21
Defines (-d name[=value])
Use this scrollable text box to define the names and optional values of preprocessorvariables:
The -d option is used to define preprocessor variables from the command line. value canonly 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.
Using the Compiler 119
Fortran User Guide
Preprocess to file (-P)
The -P option directs the compiler to place the output of the preprocessor in a file that hasthe 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 thecompiler and linker.
Verbose templates (-ptv)
This option causes the compiler to print a message to stderr whenever a template ininstantiated.
Quiet (-q)
The Absoft C/C++ compiler normally displays information to standard output (theWorksheet window) as it compiles an application. Enabling the -q option will suppressany messages printed to standard output. Errors will still be printed to the standarddiagnostic output, however.
121
Fortran User Guide
CHAPTER 6
Porting Code
This chapter describes issues involved in porting FORTRAN 77 code from otherplatforms. One of the major design goals for Absoft Fortran 77 is to permit easy portingof FORTRAN 77 source code from mainframe computers such as VAX and IBM, andfrom workstations such as Sun. The result is the rich set of statements and intrinsicfunctions accepted by Absoft Fortran 77. The last section of this chapter describesMacintosh-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 thedifferences between the Macintosh and other environments such as floating point mathprecision or stack-size issues. See the section Other Porting Issues later in this chapterfor special considerations when porting code to the Macintosh. In addition, you may wantto use this option:
-C Check array boundaries and generate better runtime errors. Using this optionmakes programs slightly larger and they will execute slower.
If you want to use the Absoft debugger, Fx, add the -g option to generate debugginginformation.
PORTING CODE FROM VAX
Absoft Fortran 77 automatically supports most of the VAX FORTRAN languageextensions. Below is a list of key VAX FORTRAN extensions that are supported and alist of those that are not supported. For a complete list of VAX extensions, refer toAppendix H. Using various options, the compiler can also accept VAX Tab-Formatsource lines and/or 132-column lines. Otherwise, only ANSI FORTRAN 77 fixed formatlines 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
122 Porting Code
Fortran User Guide
• “!” 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 agroup of compiler options collectively referred to as the “VAX compatibility options”,listed below. When using the Commando interface for the compiler, they may be invokedby 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 withthe file vmslib.o in the FLibraries folder. They are:
DATE subroutine returns current date as CHARACTER*9IDATE subroutine returns current date as 3 INTEGER*4TIME subroutine returns current time as CHARACTER*8SECNDS subroutine returns seconds since midnightRAN function returns random number
The following list of VAX FORTRAN “qualifiers” shows the equivalent Absoft Fortran77 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-> forthe ≥ character)
Porting Code 123
Fortran User Guide
/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 foruntyped 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 sizefor a file by pressing -Y while editing a file and typing the tab size for the file. Formore 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 -N51options 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 languageextensions. Below is a list of key VS FORTRAN extensions that are supported and notsupported. Using a compiler option, Absoft Fortran 77 can also accept VS FORTRANFree-Form source lines which use 80 columns, otherwise, only ANSI FORTRAN 77fixed 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 “&”
124 Porting Code
Fortran User Guide
• 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 thesecompiler 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 -N3option 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 languageextensions. Below is a list of key Microsoft FORTRAN extensions that are supported andnot supported. Absoft Fortran 77 does not have the code size restrictions found in thesegmented 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
Porting Code 125
Fortran User Guide
• 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 byusing 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 writebinary sequential files with no internal structure, do not use the -N3 option which includesrecord length within sequential, unformatted files.The following list of Microsoft FORTRAN metacommands shows the equivalent AbsoftFortran 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-linecharacters within the file may not match the return character (decimal 13 or Control-M)
126 Porting Code
Fortran User Guide
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 theFind 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 languageextensions. Below is a list of key Sun FORTRAN extensions that are supported and notsupported. The Sun FORTRAN compiler appends an underscore to all external names toprevent collisions with the C library. Absoft Fortran 77, by default, does not append anunderscore to maintain compatibility with the Macintosh toolbox and other MPWlanguages. 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 andlanguage 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 thefollowing lines in the Worksheet window:
translate " " ∂n <old.f >new.fcatenate <new.f >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 NextStepoperating system for either Motorola or Intel microprocessors had the same optimizationsand language extensions as Absoft Fortran 77. The object-oriented extensions of the
Porting Code 127
Fortran User Guide
NeXT compiler are specific to the NextStep environment and are not supported withAbsoft 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/6000computer and had the same optimizations and language extensions as Absoft Fortran 77for Windows with Intel or PowerPC processors. The compilers are 100% sourcecompatible.
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 extensionsas Absoft Pro Fortran for the Macintosh with PowerPC. The compilers are 100% sourcecompatible.
PORTING CODE TO/FROM OTHER MACINTOSH SYSTEMS
Language Systems Fortran
Absoft Fortran 77 and Language Systems Fortran share many extensions implemented inother compilers. In addition, Absoft Fortran 77 automatically supports most of theLanguage Systems Fortran specific language extensions. Below is a list of key LanguageSystems extensions that are supported and a list of those that are not supported. For acomplete 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
128 Porting Code
Fortran User Guide
Over the past 15 years, Absoft has offered several different compilers for a number ofMacintosh environments. This section outlines some of the differences between theseproducts.
MacFortran This 68000 compiler supported ANSI FORTRAN 77 and compiledprograms directly from the Finder without using MPW. Althoughit lacked optimizations and support for many of the extensions inAbsoft Pro Fortran for Macintosh with PowerPC, it compiled veryfast and was easy to use.
MacFortran/020 This 68000 compiler was the same as MacFortran but it could alsoproduce faster code for 68020 and 68030 systems that incorporateda floating point unit.
MacFortran II This 68000 compiler is very similar to Absoft Pro Fortran forMacintosh with PowerPC. It supports many of the sameoptimizations and extensions, but is designed for 68000 basedMacintoshes.
OTHER PORTING ISSUES
Not all porting and compatibility issues can be solved automatically by Absoft ProFortran or by using various option combinations. There are six issues that must beaddressed on a program-by-program basis for the Macintosh computer:
Memory Management Tab Character SizeStack Issues Numeric PrecisionFile and Path Names Floating Point Math Control
Memory Management
Porting Code 129
Fortran User Guide
When an application is running on the Macintosh, there is a block of memory set asidefor the application as shown in Figure 6-1. It may not be enough for large programs orones that use extensive amounts of stack space (i.e. large local arrays).
STACK
FreeMemory
CODEand
HEAP
Total memoryfor an
application
Simplified memory model for Macintosh applicationsFigure 6-1
The size of the total block of memory is defined in the SIZE resource for an applicationand is set automatically by the Absoft Pro linker. The linker makes this determinationbased on the size of the program itself, its data requirements, and an estimate of the stackrequirements. The amount allocated to the stack can be adjusted with the SetPrefs tool(see THE SETPREFS TOOL section in the chapter The Macintosh Runtime WindowEnvironment). 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 Filemenu to display a dialog box similar to that in Figure 6-2.
130 Porting Code
Fortran User Guide
Get Info dialog for an applicationFigure 6-2
As a general rule, set the size to a value larger than the size of the code and data. Tochange the SIZE resource automatically when an application is generated, see the chapterMacintosh Programming.
Stack Issues
If a program “crashes”, displays no text, shows blank menus or gives a system error suchas 28, often it is caused by stack size limitations. You can get around this limitation inone of three ways:
• For applications or tools, compile with the -s compiler option toallocate all local variables in static, heap memory instead of the stack.This should solve any stack problems but it may increase the amountof memory required by the application.
Porting Code 131
Fortran User Guide
• For tools, since the MPW stack is also used for tools, increasing theMPW stack will give tools more stack space. To do this, use the toolutility SetShellSize which is included as part of MPW — just typehelp SetShellSize in the Worksheet window and follow theinstructions.
• For applications or tools, you can use the Macintosh memory managercalls to dynamically allocate free memory for large data structures.This is a Macintosh-specific solution. For more information, see thechapters 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 andspaces. 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 arunning application, the file name can be used without having to specify a path as in thisexample 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 areused to specify files in other folders. Each component of a path name is separated by acolon. A full path name always begins with the name of a volume and includes each ofthe folder names in the path to the file. A full path name is a complete and unambiguousidentification for a file. Another type of path name is a partial path name which describesthe path to a file starting from the current folder. It must begin with a colon and it ispossible to specify a parent folder with a double colon.
Hierarchical folder structure of the volume MyDiskFigure 6-3
132 Porting Code
Fortran User Guide
The following two OPEN statements in the Analyzer programs open the same file as shownin 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 thevolume or the folders above those referenced. The double colon (::) moves up the tree tothe 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 moreinformation about file, volume, and path names, see the File Manager chapter of InsideMacintosh.
You do not have to specify a filename in an OPEN statement. Use FILE="" for a standardfile dialog to be displayed which prompts for a filename. For example, the followingstatements 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 tospecific file types (see the OPEN STATEMENT section in the Input/Output andFormat 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”.
Porting Code 133
Fortran User Guide
Tab Character Size
Absoft Pro Fortran expands each tab character in a FORTRAN source file into theequivalent number of spaces during compilation. The size of a tab character isdetermined from the following list in order.
• From the source file itself: All MPW document files, includingFORTRAN source files, have a resource that contains the tab size forthe file. It is initially set to the MPW environment variable Tab butmay be changed with the Format command in the Edit menu.
• From the environment variable Tab, which is initially set to 8 spaces inthe UserStartup•Fortran file, but may be changed with an MPWstatement 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 isgiven a tab size of 8.
Floating Point Math Control
This section describes the basic information needed to control the IBM PowerPCFloating Point Unit (FPU) built into the Macintosh. The FPU provides a hardwareimplementation of the IEEE Standard For Binary Floating Point Arithmetic (ANSI/IEEEStd 754-1985). As a result it allows a large degree of program control over operatingmodes. Complete information on the FPU can be found in the PowerPC 601 RISCMicroprocessor User's Manual. There are two aspects of FPU operation that can affectthe performance of a FORTRAN program:
Rounding direction
Exception handling
A single subroutine is provided with the compiler which is used to retrieve the currentstate 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 ofthe floating point unit and 1 to set it to a new state.
arg is an INTEGER variable that receives the current state of thefloating point unit if cmd is 0 and passes the new state if cmd is 1.
134 Porting Code
Fortran User Guide
Rounding Direction
The first aspect of FPU operation that may affect a FORTRAN program is roundingdirection. This refers to the way floating point values are rounded after completion of afloating point operation such as addition or multiplication. The four possibilities asdefined in the fenv.inc include file are:
FE_TONEAREST round to nearestFE_TOWARDZERO round toward zeroFE_UPWARD round toward +infinityFE_DOWNWARD round toward -infinity
Exception Handling
The second aspect of FPU operation that affects FORTRAN programs is the action takenwhen 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 (eitherInfinity or NaN) and continue program execution. Alternatively, the FPU can beinstructed to generate a floating point exception and a run time error when an exceptiontakes place. This is known as enabling the exception. The five exceptions that can occurin a FORTRAN program with the IBM PowerPC 601 are:
FE_INEXACT inexact operationFE_DIVBYZERO divide-by-zeroFE_UNDERFLOW underflowFE_OVERFLOW overflowFE_INVALID invalid argument
135
Fortran User Guide
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 MPWBuild and ACM commands. This chapter details the MPW tools available for advancedprogramming and linking using the Worksheet. The compiler, the linker, and the Fsplitutility are described. You can use each tool in the Worksheet through an MPWcommand: the syntax and a description of each command is listed below. To use thesetools, you must have a complete understanding of the topics discussed the chapter Usingthe Worksheet, or have read the Macintosh Programmer’s Workshop Manual listed inthe bibliography appendix.
AN OVERVIEW OF PROGRAM BUILDING
There are several different ways of building an application or MPW tool with Absoft ProFortran. The general overview of building a completed application is as follows:
Create source files and compile them into object files with the properinterface and include files. See the section on Creating Object Fileslater in this chapter.
Create non-code resources with Rez and DeRez. See the section onWorking with Resources in this chapter.
Create the executable program by using the linker to link object files withthe necessary resources and library routines from the Toolbox. Formore information on using linkers, see the section on LinkingPrograms, 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 operatingsystem and interface are all important components of an application. Output from toolssuch as Lnk, Link, and Make are combined with your program code to create a Macintoshapplication.
Macintosh applications and document files have two forks: a data fork and a resourcefork, 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 containsinformation that is interpreted by the application that created the file. A resource forkcontains information about a sequence of discrete objects called resources. When you
136 Building Programs
Fortran User Guide
create a PowerPC program in Absoft Pro Fortran, the data fork will hold the programcode 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 resourceis a collection of information used by the Macintosh system, such as menus, windowdefinitions, or icons. These and other types of special information are stored in theresource fork of a program file. The application itself may use some of the resourceswhile the Finder, or even other applications, may use the resources for gettinginformation 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 methodof 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 basedon a textual resource description file. Rez is documented in this chapter along withDeRez, 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 ismade 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 belaunched when the file is double-clicked.
CREATING OBJECT FILES
After you create and edit source files in the MPW Editor (see the chapter Using theEditor), or port files from other environments (see the chapter Porting Code), these filesare compiled using the Absoft Pro Fortran compilers (described in the chapter Using theCompiler).
The compilers are invoked by using one of the commands f77, f90, or acc — thesecommands control both the compilers and the Lnk tool (see the section below on LinkingPrograms). The features of these commands simplify the process of creating finishedapplications, 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 thesecommands, follow these command syntax guidelines:
f90 [option…] [file…]
f77 [option…] [file…]
acc [option…] [file…]
Building Programs 137
Fortran User Guide
where option… represents one or more of the compiler options described in chapterUsing the Compiler. These options must begin with a minus sign (-); if more than oneoption is used, separate each option with a space. Also, some arguments appended to anindividual option, such as a filename, may need to be separated from the option letterwith a space.
When these commands are invoked in the Worksheet, each file will be compiled togenerate an executable application or tool. The resulting application or tool will benamed 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 inthe file Link.Out. To compile Hello.f with the static local storage option, and generatea tool named Hello, enter:
f77 -s -tool -o Hello Hello.f
The option, -o name, specifies the name of the executable file overriding the defaultname 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 inconjunction 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 thatexecute 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 compilercommand with the -c option. This will suppress any linking functions and an executablefile 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 sourcefile has been compiled into an object file, it contains object code as well as any symbolicexternal references not known at compile time.
Since the linker is directly accessed by the compiler commands, any set of options maybe 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 nothave to be specified.
-tool Use this option to generate an MPW tool instead of an application.
138 Building Programs
Fortran User Guide
-plainappl Use this option to generate an application without the MRWE librarieslinked. This is required when compiling a FORTRAN application thatdoes not use MRWE, accessing the Macintosh toolbox routinesdirectly.
-g Generates debugging information for Fx, the Absoft symbolic debugger.
For a complete list of compiler options and descriptions, see Using theCompiler 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 portcode from other environments, you may want to split large, cumbersome source files intoone procedure per file. This can be done using the Fsplit tool. The command syntax forthe tool is shown below.
Fsplit [option…] [file…]
Fsplit splits FORTRAN source files into separate files with one procedure per file. Thefollowing command line will generate individual files for each procedure:
Fsplit largefile.f
A procedure includes block data, function, main, program, and subroutine programdeclarations. 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. Anexisting block data file with the same name will not be overwritten.
• Newly created procedures (non-blockdata) will replace files of thesame 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 tabsize 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.
Building Programs 139
Fortran User Guide
-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, perhapscompiled with different compilers, it is important to minimize the use of features whichare 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 iswasteful or may cause incorrect operation. Complete documentation for Ftnchek can befound in the file ftnchek.doc.
Ftnchek [option…] [file…]
In the following list of options, the default setting is listed in parentheses after thedescription.
-[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 )
140 Building Programs
Fortran User Guide
-[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 checking1=check number of arguments2=check type of arguments3=check number and type of arguments
-array=dd check subprogram array arguments where: (3)0=no checking1=check number of dimensions2=check type of array3=check number of dimensions and type of array
-columns=dd maximum line length processed. (72)-common=dd COMMON block checking where:. (3)
0=no checking1=check data type of variable2=check size of variable3=check data type and size of variable
-usage=dd variable usage where: (3)0=no checking1=check if variable is used before it is defined2=check if variable is declared but never used3=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 anyof the extensions to the FORTRAN programming language incorporatedby the Absoft compiler.
LINKING PROGRAMS FOR POWERPC
Building Programs 141
Fortran User Guide
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 toolthat provides this feature is the Lnk tool, or otherwise called the Linker. This tool is alsoused 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. TheLinker creates (or replaces) program code and places the object files as linked segmentsinto the data fork of the output file. The linker then assigns the new application a type (bydefault ‘APPL’ for application) and a creator (‘????’). The default output file name isLink.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 anordinary object file only, it contains object code and symbolic references to globalvariables and identifiers unknown at compile time. If you execute one of these commandswithout the -c option, the Lnk command is automatically invoked, creating theexecutable 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 ofnn must be a power of 2. This option is always set with nn equal to 16 when acompiler invokes the linker.
-ad nn
Use this option to align the data section to an nn byte boundary. The value ofnn must be a power of 2. This option is always set with nn equal to 16 when acompiler invokes the linker.
-export name
142 Building Programs
Fortran User Guide
This option is used when creating shared libraries. See the section CreatingLibraries for PowerPC for details.
-O Use this option to direct the linker to organize your subprograms in such away that the shortest possible procedure references are taken to minimizepage faults and/or cache inconsistencies.
-xm library
This option specifies that a static library is to be created. See the sectionCreating Libraries for PowerPC for details.
-xm sharedLibrary
This option specifies that a shared library is to be created. See the sectionCreating Libraries for PowerPC for details.
-sym (on|off)
This option controls the output of the auxiliary symbol file. See the LinkerOptions paragraph in the Debugging section of the chapter MacintoshProgramming 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 linkerinformation. The default is -fast on and indicates to use memory.
-dead (on|off)
This option controls whether the linker removes unreferenced routines anddata. 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 globalsymbol names.
-domunchThis option inserts code to call static constructors and destructors for C++classes when using the Absoft C/C++ compiler.
-savecfrg
Building Programs 143
Fortran User Guide
This option directs the linker to leave the applications cfrg resourceunchanged.
-saveSIZE
This option directs the linker to leave the applications SIZE resourceunchanged.
-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 datafork for the bss section.
-weak <filename>:<symbolname>
This option specifies that the <symbolname> imported from <filename> isweak. For more information on weak loader symbol binding, consult InsideMacintosh: PowerPC System Software.
-modlib <filename>[+<curVer>][-<impVer>][!][~]
This option sets flags in the executable file which direct the loading of importlibraries specified by <filename>. +<curVer> and -<impVer> specify thecurrent version and the implementation version of the import library,respectively. ! specifies that the library has init priority. ~ specifies that thelibrary is weak. The options must be given in the order presented. For moreinformation on import libraries, consult Inside Macintosh: PowerPC SystemSoftware.
-share <int>
This option indicates whether the data section of an application can be sharedwith other applications. <int> must be one of the following:0 never share1 context share (default)2 task share3 team share4 global share
For more information on the PEF format, consult PEF—PowerPC Executable FormatReference Specification.
BUILDING PROGRAMS
Building a program describes the process of compiling and linking a program into anexecutable file. The f90, f77, or acc commands, or the Compile and Compile and Launchcommands are ideal for compiling and linking a small number of source files. However,
144 Building Programs
Fortran User Guide
when there are many source files or when source files are in mixed languages, such asFortran 90/95 and the C programming language, these commands become impractical touse. Working with a large number of source files or files from different languagesrequires that you can easily tell how they are compiled. When you use the buildcommands discussed below, these commands work with a special text file called amakefile.
A makefile is a text file that contains a list of source files and rules. The list includes theobject files and how they are combined, along with the variable names and commentsfrom the object files. The makefile describes the dependencies between each source filein 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 commandfrom the Worksheet, MPW automatically creates a makefile containing a list of thecommands needed to compile and link an application, tool, or desk accessory. You alsohave the option of creating makefiles from scratch, using the MPW scripting featuresdescribed in the MPW Reference Manuals. However, the easiest way to create a makefileis 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 timeto help manage the compilation of numerous source files. Since the makefile is generatedas a text file, it can be opened in a text window and changed as the program grows in sizeor 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 itemCreate Build Commands… is also available as an MPW command, ACM, and can be useddirectly from the Worksheet.
Modifying Makefiles
As source files, resources and libraries are added to a program, you may need to modifysome parts of the makefile. For example, you may need to append additional compiler orlink options to a file.
Format of a Makefile
In order to modify a makefile, you need to know the various types of information that themakefile contains. Basically, the makefile contains information about the separate piecesof 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 withprerequisite files. A target file is dependent on certain components to run; these are theprerequisite files and the rules that connect the files.
Building Programs 145
Fortran User Guide
The prerequisite files are the source files, library files and resources on which a target fileis based. When these files are modified, the target file must be rebuilt. A target'sprerequisites may, in turn, be targets with their own prerequisites.
The dependency rules are the rules that connect all prerequisite files to a target file, andinclude 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 makefilecan contain one or more roots. Variable definitions and comment lines are also includedin a makefile.
Create Build Commands
When you choose the Create Build Commands… from the Tools menu, the following dialogappears:
Figure 7-1ACM dialog
This dialog operates in exactly the same manner as the Compile dialog described in detailin 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 ACMdialog box may be ignored.
146 Building Programs
Fortran User Guide
ACM Command
The ACM command is an implementation of the Create Build Commands… item in the Toolsmenu. When this command is issued, the makefile program.make is created — theparameter program will be the name of the program. The makefile includes the sourceand 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 inFORTRAN. This option does not appear in commando dialog.
-sym on
Creates build commands that construct an object containing symbolic debuggerinformation 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 andinput. This is the default and does not have to be specified.
-library
Creates an XCOFF static library. See the section Creating Libraries forPowerPC later in this chapter for details.
-sharedLibrary
Creates a PEF shared library. See the section Creating Libraries for PowerPClater in this chapter for details.
-ci dir
Adds dir to the C/C++ include paths.-fi dir
Adds dir to the FORTRAN include paths.
Building Programs 147
Fortran User Guide
-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. Seethe section Creating Libraries for PowerPC later in this chapter for details.
Build ( B)
The Build… command builds a program, using those source files that have been modifiedsince you last built the program. When selected a dialog box will prompt you to type inthe name of the program.
Figure 7-2Dialog box for build
When you click the OK button, the program will be built. A new makefile will beautomatically created that shows the dependencies between the source files and thecommands needed to build the program. Before the application is built, MPW willautomatically save any windows and other status information.
BuildProgram command
BuildProgram is implemented as the Build… menu item in the Tools menu. The commandbuilds the program with a transcript of the build including timing information andcommands used to do the build, and writes this information to standard output. Thecommand and options are passed directly to the Make tool, which will then build theprogram with the existing makefile. If a makefile does not exist for the program, thedefault makefile name Make.file is used. If an error occurs in the build process, the statusvalue is returned. The syntax for the command is:
BuildProgram program [option]
The -e option can be specified to completely rebuild everything, regardless of dates ortemporary 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 thespecified target files. The Make tool reads a makefile created by the ACM command, anddetermines which components of the program need to be rebuilt. The Make script thenrebuilds only those components of a program necessary. The command syntax of Make is:
148 Building Programs
Fortran User Guide
Make [ option…] [targetFile…]
Options for the makefile are as follows:
-d name [=value]
Define a variable name with the given value. This variable defined fromthe command line takes precedence over the same variable in themakefile.
-e Rebuild everything regardless of dates. The program is rebuilt, ignoringany other up-to-date object files or other temporary files that exist.
-f makefile
Read dependency information from makefile. More than one -f optioncan be specified; all information is treated as if it were contained in asingle 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 thedependency tree. This option will override the normal Make output.
Building Programs 149
Fortran User Guide
The Snowflake program
This tutorial will guide you through the steps required for creating a makefile andbuilding 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 thecurrent directory.
Select the…Examples:FExamples:from the Directory menu.
Execute Create BuildCommands. Select the command Create BuildCommands… in the Tools menu.
Name the executable file. Type “Snowflake” in the ProgramName box.
Select the two source files that areneeded for the Snowflake example.One file contains the FORTRANsource code and the other hasresource information.
Click the Source Files… button andthen double-click on each of theSnowflake.f and Snowflake.r files.Click on the Done button.
Add the ColorPickerLib shared library. Click the Libraries… button and thenOtherLibraries... Navigate to the MPWLibraries:SharedLibraries folder. Clickon All Libraries and add ColorPickerLib.
Create the makefile. Click the ACM button or press theEnter key. The name of the makefileis Snowflake.make.
Select the makefile to build theSnowflake example.
Select Build… from the Toolsdirectory and type “Snowflake” inthe Program Name box.
Compiler and linker options cannot be selected directly when building a program usingthis method. To use compiler options, the makefile must be edited as follows:
What to do How to do it
Change the makefile for Snowflaketo compile with basic optimizations.
Edit the file Snowflake.make andchange the line near the top of thefile from FFLAGS= to FFLAGS="-W".
150 Building Programs
Fortran User Guide
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 moreroutines, that are maintained in a single file — a library. When a library file is presentedto the linker, modules that are required to satisfy unresolved external references areselected for inclusion into the application file. The advantage of a library is that onlythose modules that are required to satisfy unresolved external references are linked intothe application. The FORTRAN 77 runtime libraries, libfmath.o and libfio.o, areexamples of static libraries. Not every FORTRAN 77 program requires a hyperbolictangent 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 inobject modules. The difference is that the elements of the library are not linked into thefinal 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 andseveral applications can share the same library. The disadvantage is that the dynamic orshared library must be available on every computer where the application is to be run.
Note: Dynamic or shared libraries are not supported with CabonLibapplications that link against mrwe.o or any ProFortran I/O library.
The Lnk command, introduced earlier, is used to create static library files by combiningmultiple object files into a single library file with type 'OBJ' (this is the type generated byf77 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 logicallyequivalent 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 exportedin the shared library.When used in conjuction with the -xm library option, this option specifiesthe 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 -exportname option described above.
Building Programs 151
Fortran User Guide
-p Use this option to display progress information to the diagnostic output.-w Suppresses all warning messages.-curver <int>
This option sets the current version in the import library. For moreinformation on import libraries and version checking, consult InsideMacintosh: PowerPC System Software.
-defver <int>
This option sets the definition version in the import library. For moreinformation on import libraries and version checking, consult InsideMacintosh: PowerPC System Software.
-impver <int>
This option sets the implementation version in the import library. For moreinformation on import libraries and version checking, consult InsideMacintosh: PowerPC System Software.
Shared libraries have a default type of “shlb” and a default creator of “cfmg”. They mustbe placed in the Extensions folder of the System Folder in order for applications that use theprocedures 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, atext file that can be modified and changed. This file is compiled by the Rez tool into afinished resource file.
Rez can also combine multiple resource files into a single resource file, delete andmodify resources, and append resources to an application file that was created with theLnk tool. This next example, from the Snowflake.make file, compiles the resourcedescription 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 resourcesusing text commands. The format of a resource description file is similar to the outputfrom the DeRez tool. Options for the Rez tool include:
152 Building Programs
Fortran User Guide
-o name
Use this option to specify the name of the output file instead of the defaultRez.Out. name must appear after the -o option as shown in the examplebelow.
-append
This option causes Rez to append resources to the output file rather thanreplacing 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 theMacintosh Programmer's Workshop Manual. See the bibliography inAppendix 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 bemodified and then recompiled with Rez. Each resourceDescriptionFile can containdeclarations for specific resources such as the standard Macintosh resources described in{RIncludes}Types.r and {RIncludes}SysTypes.r. Some options for the DeRezcommand are listed below.
-only type [(ID1[:ID2])]
This option causes DeRez to read only the resources of the type and IDspecified. The option may be used repeatedly to specify more types. Type is aquoted resource type such as 'MENU' and ID1 and ID2 specify a range ofresource ID numbers. The entire option parameter must be quoted if an ID orID range is specified.
-only type
The type in this form of the -only option does not need to be quoted, butdoes not provide choosing specific IDs.
Building Programs 153
Fortran User Guide
-skip type [(ID1[:ID2])]
With syntax identical to the two forms of the -only option above, this optionexcludes the specified resources. The option may be used repeatedly toexclude 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 theMacintosh Programmer's Workshop Manual. See the bibliography inAppendix D for information.
The following example decompiles the MENU resources of the application Hello in theFExamples folder and displays the textual representation to standard output. TheTypes.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 standardMacintosh resources. It is located in the RIncludes folder. The following line placed incolumn 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 aunique icon for an application instead of the default application icon. The followingexample defines the ICN#, BNDL, and FREF resources. The resource FSMP can have anyname but must match the creator that is set with the -c type linker option. See thechapter “Finder Interface” in Inside Macintosh for details about how these resources areused 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"
};
154 Building Programs
Fortran User Guide
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 theMacintosh Runtime Window Environment (MRWE) by adding these resources to theMRWE.r file and rebuilding the MRWE library as described in the Read Me file of theMRWE folder.
Building Programs 155
Fortran User Guide
All applications that use MRWE have the following balloon help for its icon when shownin the Finder:
The help is simply defined in a ‘hfdr’ resource with ID -5696. This code is from theMRWE.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 examinedto determine how much memory the application requires. The SIZE(-1) resource from thefile Snowflake.r is shown below and sets the minimum memory size to 48K and thepreferred to 64K. These are the values that appear in the Get Info… dialog box from theFinder. The other elements of the SIZE(-1) resource are documented in the EventManager chapter of Inside Macintosh, (volume VI) listed in Appendix D.
156 Building Programs
Fortran User Guide
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 theMRWE.r file and rebuilding the MRWE library as described in the Read Me file of theMRWE folder. By default, MRWE has a SIZE(-1) resource that specifies 384K for theminimum and preferred sizes for applications. This value may be increased for largeapplications 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, anyprogram can also be compiled as an MPW tool that uses the Worksheet window, or anyother window, for standard input and output. Although generating an application isrecommended for most programmers, there are advantages and disadvantages forgenerating a tool.
Advantages of generating a tool
A compiled program executing as a tool runs within MPW. This meansfaster program start-up since the Finder does not have to handle anotherapplication.
Standard output (FORTRAN preconnected units 5, 6, 9, and *) isdisplayed on the front-most window and can be saved and edited like allwindows.
A tool can access some run time features such as command line argumentsand environment variables from the MPW environment as described in theoptional Macintosh Programmer's Workshop Manuals.
Building Programs 157
Fortran User Guide
Disadvantages of generating a tool
A tool requires MPW to execute. This is not a problem during programdevelopment or for single-machine installations but can limit its use as acompleted 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 moredetails.
The easiest way to generate a tool is to select the MPW Tool option in the Output File boxof the Pro Fortran compiler Commando dialog as in the figure below.
Commando dialog for building an MPW toolFigure 7-3
There is a similar -tool option for the ACM command. It is the MPW linker, invokedautomatically when compiling, that determines if a tool or an application is to begenerated. This section will explain other details such as initialization, linking, andmemory management.
158 Building Programs
Fortran User Guide
Tool Initialization
This section about tool initialization applies only to those programmers that are callingthe 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 callsshould not be made:
ExitToShell MaxApplZoneInitDialogs RsrcZoneInitInitFonts SetApplLimitInitMenus SetGrowZoneInitResources TEInitInitWindows
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 becompiled and launched as an application.
Another issue for tools is stack size. Problems with the stack when running a compiledprogram as a tool show up as system errors that may crash the machine. Getting systemerrors 28, 2, and 3 may indicate stack problems. When do compiled programs use thestack? Non-static local variables are allocated space on the stack at the beginning of theprogram unit in which they are defined. All local variables in Fortran 90/95 andFORTRAN 77 can be made static, thus avoiding this problem, by using the -s option forstatic storage when compiling or by using SAVE statements to force static storage. Notethat 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 isone solution that changes the stack size for MPW itself. You can increase the MPW stacksize by using the SetShellSize tool. For detailed information, refer to the MacintoshProgrammer's Workshop Manual.
159
Fortran User Guide
CHAPTER 8
The Macintosh Runtime Window Environment
This chapter discusses the Macintosh Runtime Window Environment (MRWE), a specialfeature 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 tocreate applications with windows and menus, you need to know how to use theMacintosh Toolbox and the Apple user-interface guidelines. When you create anapplication using MRWE, your program will automatically exhibit these features withoutthe need for intensive Macintosh programming. MRWE is convenient and flexible to use.
MRWE applications are created using the Apple Macintosh Carbon library. This allowsyour applications to have the look and feel of the classic Macintosh interface whenrunning 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 nativeenvironment.
USING MRWE
MRWE is a collection of pre-compiled Fortran routines contained in the library fileMRWE.o that you can link with your program. Applications generated by Absoft ProFortran are usually linked with this library unless you build a tool or explicitly select anApplication without MRWE as shown in the dialog box below. The Fortran source code forMRWE is in the FExamples folder and can be used as an example of how to callMacintosh toolbox routines.
160 The Macintosh Runtime Window Environment
Fortran User Guide
The Compile dialog allows you to select the format of the executable file. An executablesetting 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. Ifyour source code includes its own event loop and calls Toolbox routines, you shoulddisable 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 ablank window on the screen and, above it, a menu bar, as shown below. This window iswhere MRWE displays standard output from Fortran programs and is where all standardinput is typed. It looks like a terminal display, but allows you to see text that has scrolledoff the screen.
The Macintosh Runtime Window EnvironmentFigure 8-2
Standard input and output are preconnected to the Fortran I/O units 5, 6, 9 and *. Any ofthese except * may be connected instead to a file by specifying the unit in an OPENstatement. After closing the file on that unit, the unit will be reconnected to standardinput and output.
The Macintosh Runtime Window Environment 161
Fortran User Guide
How Your Program And MRWE Work Together
When your program is launched, control is first passed to MRWE, which sets up aMacintosh environment with menus and a window. After the window appears, theapplication begins executing your Fortran program. By default, your program is the onlyprogram active; other programs are suspended and MRWE is inactive until an I/Ostatement occurs. You cannot pull down menus, terminate the application, or use otherapplications at this point. Your Macintosh is completely dedicated to executing yourFortran program at maximum speed.During any input and output statements (i.e. READ, WRITE, ENCODE, etc.), you can eitherterminate the application with a Command-Period ( -.) or switch to other applications.When the program is waiting for you to type standard input, you also have completecontrol of the menus and normal mouse actions. If you want the ability to terminate yourapplication while it is calculating, or want to run other applications, select the -N9compiler option before compiling the program.
The -N9 compiler option turns on the timer interval feature. Your program will beinterrupted at timed intervals to check for Command-Period termination and to allowother 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 andCommand-Period checking will still occur, but only during Fortran input and outputstatements. If you are not running other programs at the same time this will not create aproblem, but if you are, the other programs may appear sluggish.
If you did not include the -N9 compiler option when compiling, and your program isexecuting lengthy calculations that you want to stop, you can regain control by using theForce Quit feature of System 7 and above. First press the Control-Option-Command keysand then the Escape key. A dialog box will appear on the screen allowing you toimmediately stop program execution. Make sure the correct application is indicated in thedialog box message. If it is not, click on the Cancel button and repeat the aboveprocedure. If your application is indicated, click on the Force Quit button, and yourMacintosh should return to the Finder. [Caution: Data in files that were open may be lostduring this procedure and it may be wise to restart the computer after you regain control.]
Force Quit Feature of System 7Figure 8-3
162 The Macintosh Runtime Window Environment
Fortran User Guide
Working With Text in MRWE
The MRWE window operates a little differently from text windows in MPW. Thewindow 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 forstandard input (i.e. one of the preconnected units), and you can only type on the last lineof the window. Any text that was already in the window when the READ statementbegan cannot be modified. You can, however, copy any text in the window to theclipboard. Also, when using the extended keyboard, the Home, End, Page Up, and PageDown keys can be used for scrolling. To insert an end-of-file character, type eitherCommand-Return or Command-Enter.
All output characters, except for the bell character (ASCII 7), are displayed in thewindow. This means that ASCII control characters such as a backspace (ASCII 8) will bedisplayed 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 isopened as an MPW document.
The MRWE window has a text limit of 30K. When this limit is reached, the oldest text inthe window is automatically deleted to make room for new output. See the sectionentitled 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 adescription of the commands performed by each item within these default menus.
File Menu
The File menu contains commands for saving and printing the text inthe window.
Save ( S)
This command saves the MRWE text to an MPW document file — a text file. Thewindow 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 SetPrefsTool section later in this chapter.
The Macintosh Runtime Window Environment 163
Fortran User Guide
Save As…
This command saves the window text to an MPW document file — a text file. Itdisplays 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…( P)
To print the contents of the window to the printer, use this menu item. A dialog box isdisplayed showing the printing status. When a block of text is selected, this menuitem changes to Print Selection… and prints just the selected text rather than the entirewindow. Note that multiple copies cannot be printed on an ImageWriter in draftmode.
Quit ( Q)
This command stops execution of the application by executing a STOP statement, thusclosing all open Fortran units.
Edit Menu
The Edit menu contains the standard editing commands for cutting, pasting,and copying text.
Undo ( Z)
This command is always disabled unless a desk accessory is being used.
Cut ( X)
This command removes the selected text in the window and places it on theClipboard. Text on the Clipboard may be pasted into other applications. Like otherediting commands, this command is only available during a READ statement, and anytext that was already in the window before the READ statement began cannot be cut.
Copy ( C)
The Copy command places the selected text from the window onto the Clipboard andleaves the text of the window unchanged. Text on the Clipboard may be pasted intoother applications.
164 The Macintosh Runtime Window Environment
Fortran User Guide
Paste ( V)
This command replaces the selected text of the window with the text on theClipboard. If no text is selected in the window, the Clipboard text is inserted at theinsertion point. Like other editing commands, this command is only available duringa READ statement, and any text that was already in the window before the READstatement began cannot be pasted into.
Clear
This command clears the selected text. Like other editing commands, this commandis 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 changethe appearance of text in a window to improve viewing. A checkmark beside an item inthese 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 userinterface and allow it to communicate with other programs. Menus can be easilycustomized and messages can be sent to other programs. Before discussing these features,a better understanding of the differences between a typical Macintosh application and atypical Fortran program is necessary.
Program Organization: Fortran VS. Macintosh
Usually a program has the following structure: first, it initializes its variables, possiblyreading data from files, then it calculates, then it outputs the results. Some of these stepsmay be repeated, but the basic order of execution is linear (see figure 8-4 below). Once aprogram begins, there is typically very little interaction with the user.
The Macintosh Runtime Window Environment 165
Fortran User Guide
Initialization and data input
Calculate
Write out
results
Initialization,including menus
Dispatchthe
event
Mouse-click
Keypress
AppleEvent
EventLoop
Ask Macintosh Operating
System for thenext eventpending
Other
Typical Fortran Program Typical Macintosh ProgramFigure 8-4 Figure 8-5
The Macintosh, on the other hand, presents a very different, highly interactiveenvironment to the user. The interface provided on a Macintosh between the program andthe user allows for control and data selections to be made in a graphical manner as wellas the more traditional textual methods. The Macintosh communicates user requests tothe program through a mechanism known as an event that describes an action such asmaking 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 isrequired.
These actions are usually directed by an event loop, in which the program requests fromthe Macintosh any events pending for the program, carries out the directed action, andthen repeats the process (see figure 8-5). When no events are pending, the program willcarry out whatever other procedures it was designed to do. Some programs may simplybe idle at this stage if they are designed entirely to react to user input (such as a drawingprogram).
Unfortunately, there is much more to Macintosh programming than this simpledescription implies, and it would be necessary to add a great deal of programming toeven the simplest Fortran program to add a Macintosh look and feel to it. MRWE can addmost of these features to your program and provides facilities that allow you to addadditional features without delving into the details of Macintosh programming.
166 The Macintosh Runtime Window Environment
Fortran User Guide
MRWE Event Loop Operation
As the preceding discussion indicates, an event loop is a necessary component of aMacintosh program, and one is built into the MRWE routines. To use it, you mustprovide subprograms that this event loop can call to respond to user requests. Thissection will describe how to use this built-in event loop.
Just one call to the subroutine mrwe_EventLoop will begin this mechanism, making yourprogram behave automatically in response to user actions.
EXTERNAL recur,termCALL mrwe_EventLoop(recur,term)
where: recur is the name of a routine that will be called repeatedly whilethe event loop executes. This routine should execute quickly andreturn so that the program remains responsive to the user. Specifyzero if you do not want to use a recurrent routine.
term is the name of a routine that you want to call when theprogram terminates. Specify zero if you do not want to use atermination routine.
When using these routines, remember to declare them as external in the subprogram inwhich mrwe_EventLoop is called. After calling mrwe_EventLoop, all events will beprocessed appropriately and, if a menu item is chosen, the subprogram you haveassociated with it will be called. Before making this call, you will probably want to set upmenu items and tell MRWE which routine will respond to particular menu items. Thisprocess will be explained in the next section on Customizing Menus.
Note that mrwe_EventLoop never returns to the procedure from which it was called. Itloops endlessly, processing the events sent by the user. Your program will only end whenone of the following occurs: the user chooses to quit, one of your menu response routinesissues a STOP statement, or there is a runtime error. [Caution: mrwe_EventLoop mustnot be called more than once.]
The Macintosh Runtime Window Environment 167
Fortran User Guide
Customizing Menus
This section describes how to customize menus to suit your application. Menus and menuitems 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 youshould probably install some menus and items first. This is because after callingmrwe_EventLoop, the user will control most of what the program does next. To install amenu 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 ischosen:
INTEGER*4 mrwe_AddMenuEXTERNAL RoutineitemID = mrwe_AddMenu(menuName,itemName,Routine)
where: menuName is a CHARACTER expression that specifies the menu thatthe item will appear in. If the menu does not already appear in themenu bar, it will be created and will appear to the right of theother menus.
itemName is a CHARACTER expression that specifies the name ofthe item to be added to the bottom of the menu. If the item alreadyexists, then only the Routine can be changed.
Routine is the name of the menu response routine to be calledwhen the item is chosen, and should be declared external in theroutine from which mrwe_AddMenu is called.
itemID, the function result, is an INTEGER*4 value. If an erroroccurs, itemID is -1; otherwise, it is a value that uniquelyidentifies the menu item. The itemID is a composite of the menunumber and item number. If an EQUIVALENCE is done of itemIDto an array of two INTEGER*2 elements, the first element is themenu number and the second element is the item number.
168 The Macintosh Runtime Window Environment
Fortran User Guide
Special Characters
Certain characters have special meanings in menu item names. If you specify any of thecharacters listed below when creating the item, you must include those characters inexactly 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 menuitem to bold, italic, underline, outline, or shadow, respectively.
/ When followed by a character, invokes the item from the keyboard bypressing 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 theitem; also, see “Adding Checkmarks to Menus” later in this section.
- Makes the item a line separator when it is the first character in themenu item name; typically used as (- to disable the separator.
Special Characters in Menu Item NamesTable 8-1
Menus and the READ statement
The menu items that you install in the menu bar by calling mrwe_AddMenu will beavailable to a user of your program after your program calls mrwe_EventLoop and assoon as your menu response routines have finished responding to any menu items thathave been chosen. The user will also be able to pull down the menus while your programis in the middle of executing a READ statement on standard input (units *, 5, 6, or 9), butthe menu items will be disabled. This is because menu response routines must notexecute Fortran I/O statements while the program is in the middle of a READ statementon Standard Input.
If you know that your menu response routine and every routine that it calls does notexecute any Fortran I/O statements, you can enable the menu item even during a READon Standard Input. To do this, add a @ character to the beginning of the name of themenu item when you install it with mrwe_AddMenu.
The Macintosh Runtime Window Environment 169
Fortran User Guide
Removing a Menu or Menu Item
To remove a menu item or an entire menu, use the function mrwe_RemoveMenu:
INTEGER mrwe_RemoveMenuiresult = mrwe_RemoveMenu(itemID)
where: itemID is an INTEGER*4 expression that specifies the item to beremoved from the specified menu. It is the same value that wasreturned by mrwe_AddMenu when the item was first installed. Ifyou specify 0 for the item component of itemID, the entire menuwill be removed.
iresult is an INTEGER. The function will return a value of 0 ifsuccessful, or -1 if there was an error.
Important: When a menu item is removed, any items that come after it will be givennew item numbers. For example, in a menu with four items: if item #2 is removed, thenitem #3 becomes item #2, and item #4 becomes item #3. Any variable containing anitemID for an item after the one removed will no longer indicate the proper item. Notealso that while item numbers are renumbered when an item is removed, menu numbersdo 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 thatperforms that function (the “response routine”) is executed. This type of routine shouldbe declared as:
INTEGER FUNCTION Routine(itemID)INTEGER*4 itemID
where: itemID is the same value that was returned by mrwe_AddMenuwhen the item was first installed. This value can be helpful ifmore than one item uses the same response routine.
Your response routine is called by the function mrwe_DoMenu, which is normally calledby mrwe_DoMouseDown whenever a mouse-down event occurs with the cursor in themenu bar at the top of the screen. The mrwe_DoMenu function can also be called explicitlyat any time during the program when you want to execute the routine associated with amenu 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 themrwe_DoMenu function as follows:
INTEGER mrwe_DoMenuiresult = mrwe_DoMenu(itemID)
170 The Macintosh Runtime Window Environment
Fortran User Guide
where: itemID is an INTEGER expression. It is the same value that wasreturned by mrwe_AddMenu when the item was first installed. It isa composite of the menu and item numbers.
iresult is the INTEGER returned by the response routinemrwe_DoMenu called. If you declare your response routines asfunctions, they can return a value through mrwe_DoMenu. If youdeclare them as subroutines, you can call mrwe_DoMenu as asubroutine.
Adding Checkmarks to Menus
Checkmarks can be placed beside a menu item after it is created by calling the routinemrwe_MenuItemCheckmark:
CALL mrwe_MenuItemCheckmark (itemID,state)
where: itemID is an INTEGER*4 expression that specifies the menu itemwhere the checkmark will be placed. It is the same value that wasreturned by mrwe_AddMenu when the menu item was installed.state, is a LOGICAL expression. If state =.TRUE., a checkmarkwill be placed next to the item; if state =.FALSE., the checkmarkwill be removed.
Enabling/Disabling Menu Items
The function mrwe_MenuItemEnable is used to enable or disable a menu item:
INTEGER mrwe_MenuItemEnableiresult = mrwe_MenuItemEnable(itemID,state)
where: itemID is an INTEGER*4 expression that specifies the menu itemwhich will be enabled or disabled. It is the same value that wasreturned by mrwe_AddMenu when the item was first installed.state is a LOGICAL expression. If the state = .TRUE., the menuitem will be enabled; if state = .FALSE., the item will bedisabled.
iresult is an INTEGER. The function will return a value of 0 ifsuccessful, or -1 if there was an error.
When installing an item by calling mrwe_AddMenu, you can also disable it by adding thespecial character ( before the item name. However, this method will not work correctlywith the mrwe_MenuItemEnable function and is not recommended. Instead, install theitem as enabled, and then explicitly disable it using mrwe_MenuItemEnable.
The Macintosh Runtime Window Environment 171
Fortran User Guide
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 returnedby mrwe_AddMenu. If the routine expects a MenuHandle, this INTEGER*4 value can bederived using the function GetMHandle, passing to it the menu number as a VAL2():
RECORD /ItemID/ sdItem ! defined in the file MRWE.incEXTERNAL DefaultSettingsINTEGER*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 thefunction mrwe_LaunchApp as defined below. You can also make an application that isalready running become the front-most, active application. [Note: This function can onlybe used with System 7.]
INTEGER mrwe_LaunchAppiresult=mrwe_LaunchApp (name,front,useMin)
where: name is a CHARACTER expression that specifies the application tobe launched and can be expressed in one of the following threeways:
1) process=programName Identifies the application to belaunched; specify the path ifnecessary.
2) creator=XXXX Launches an application using itscreator type. However, if there ismore than one program with thesame creator type, the system willlaunch the first one it finds.
3) self Allows an MRWE application torefer to itself. You can use this tobring your program to the front (seeexample below).
172 The Macintosh Runtime Window Environment
Fortran User Guide
front is a LOGICAL expression that determines whether thespecified application should be the frontmost application. Iffront=.TRUE., the application will become the frontmostapplication. If the application is not currently running, it will belaunched in front of all other applications. If the application isalready running, it will become the frontmost application. Iffront=.FALSE., the position of the application will remainunchanged. The menu bar at the top of the screen shows themenus of the frontmost application.useMin is a LOGICAL expression that refers to the amount ofmemory needed to run the program. If useMin=.TRUE., then theprogram will be launched if the minimum amount of memoryspecified is available. If useMin=.FALSE., then the program islaunched only if the preferred amount is available in the system.These values can be viewed and changed in the Finder byselecting the application’s icon and choosing Get Info in the Filemenu. If the program is already running, useMin will be ignored.
iresult is an INTEGER error code indicating problems that mayprevent launching the application. (See Table 8-6 later in thischapter 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 theprogram 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 communicatewith each other. By using this feature, you can have your applications send messages toand receive messages from other applications. MRWE allows you to use both thestandard messages defined by Apple Computer and to define your own messages. Thissection will describe how these events (or messages) are classified, what information youmust specify to transmit an event successfully, and examples of how to send and receivevarious events.
The Macintosh Runtime Window Environment 173
Fortran User Guide
Apple Event Target
The application to which you send an Apple Event is called the target and is specifiedsimilarly to the way name is specified when launching an application (see “LaunchingOther Applications” above):
Target Specification Description
process=programName Sends the message to the application whose name isspecified; include the path if necessary.
creator=XXXX Sends the message to an application whose CreatorID is specified.
sender Sends the message to the application that sent thelast Apple Event received by your application.
browser Shows the Browser dialog box, allowing the user atruntime to select any currently running applicationto send the Apple Event to.
browser=prompt Shows the Browser dialog box with a custom promptmessage 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 EventsTable 8-2
Apple Event Class and ID
The class and ID of an event indicate the action to be carried out—what the senderwants the target application to do. The class is a category of events that perform relatedfunctions. For example, Finder events make the Finder perform specific tasks such asrestarting or shutting down the computer. The class and eventID arguments arespecified with CHARACTER*4 values. For Finder events, the class is indicated by theabbreviation 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. Forexample, an Open Document or Print Document event must specify which document toact on; this is called extra information. Events can be classified according to the kind ofextra information required, if any. The following table shows the three kinds of extrainformation supported by MRWE and how they are represented as INTEGER values.
174 The Macintosh Runtime Window Environment
Fortran User Guide
Kind Value Description
signal 0 A signal event needs no extra information. It signals arequest to do something or indicates that something has beendone. For example, an application can tell anotherapplication to quit.
document 1 A document event operates on a document. The name of thedocument being operated on must be specified. For example,one application can tell another application to print adocument.
text 2 A text event includes a character string. Two MRWEapplications can pass information back and forth using textevents.
Kind of Extra Information for an Apple EventTable 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 theApple Events feature can send or receive at least four basic events called Required AppleEvents: Open Application, Open Document, Print Document, and Quit Application.MRWE supports some of the standard Apple Events and also allows you to define yourown events. It allows you to send these events to other programs and to specify routinesthat will respond if one of these events is received by your application (see ReceivingApple Events later in this section). Required Apple Events is a subset of the Core classof Apple Events—the latter is identified by the abbreviation “aevt”.
Following is a table of common Apple Events, their class, event ID, and extrainformation specifications, and a brief description of what they do.
The Macintosh Runtime Window Environment 175
Fortran User Guide
Event name Class EventID
Kind ofextrainfo
What the event does
Open Document aevt odoc document Tells the target application to open thespecified document.†
Print Document aevt pdoc document Tells the target application to print thespecified document.†
OpenApplication
aevt oapp signal Tells the receiving application it has justbeen opened; usually causes an untitleddocument to appear.†
Quit Application aevt quit signal Tells the receiving application to begin theprocess of quitting.
Do Script misc dosc text Tells an application to perform actionsspecified in a scripting language, such asMPW’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 computerin 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 ThisMacintosh” window.*
Show Clipboard FNDR shcl signal Tells the Finder to show its clipboardwindow.*
† When an application is first launched, it will immediately receive one of these three events. Open Application isonly sent when neither Open Document nor Print Document will be sent upon launch. When MRWE launches anapplication, 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 allwork the same as the corresponding Finder menu items.
Common Apple Event SpecificationsTable 8-4
Sending Apple Events
An Apple Event can be sent from one application to another as follows:
INTEGER mrwe_SendAEiresult=mrwe_SendAE(class,eventID,extraKind,target,extraInfo)
176 The Macintosh Runtime Window Environment
Fortran User Guide
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 tosend, such as 'odoc' for an Open Document event or 'quit' for aQuit Application event.
extraKind, an INTEGER, specifies the kind of extra information, ifany, that needs to be sent along with the event. Its value can be 0for a signal event, 1 for a document event, or 2 for a text event.
target, a CHARACTER expression, identifies the application thatthe event is sent to.
extraInfo, a CHARACTER expression, is the extra informationneeded for certain kinds of Apple Events.
iresult is an INTEGER error code indicating problems that mayoccur while sending the event, such as an inability to send theevent or the target application’s inability to receive the eventproperly. (See Table 8-6 for a list of error codes.)
For example, you could send an Apple Event from an MRWE application to anyapplication which understands Apple Events, and tell it to print a certain text file. Tohave your program tell Microsoft Word™ to print the document called results, youwould 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 targetapplication (Microsoft Word), the second and third arguments define the class and eventID, and the fourth and fifth arguments indicate that the event is a document event andspecify the name of the file.
Receiving Apple Events
MRWE provides a mechanism for receiving Apple Events, but it is up to you todetermine how your program will react when it receives a event. When using AppleEvents, you must specify routines that respond to particular events, just as you wouldspecify a response routine when adding menu items (see “Customizing Menus” earlier inthis chapter). For example, you may write one routine to respond to Open Documentevents and another to respond to Print Document events. You need to tell MRWE whichevents you want to respond to and the name of the routine that will handle the event. Youdo this by installing an Apple Event response routine using the functionmrwe_AddAppleEvent.
The Macintosh Runtime Window Environment 177
Fortran User Guide
LOGICAL mrwe_AddAppleEventEXTERNAL Routinelresult=mrwe_AddAppleEvent(class,eventID,extraKind,Routine)
where: class, a CHARACTER*4 expression, identifies the category of theevent to be received.
eventID, a CHARACTER*4 expression, identifies which eventwithin the class will be received, such as 'odoc' for an OpenDocument event or 'quit' for a Quit Application event.
extraKind, an INTEGER, specifies the kind of extra information, ifany, that will be received along with the event. Its value can be 0for a signal event, 1 for a document event, or 2 for a text event.
Routine is the name of the response routine MRWE will callwhen the event is received, and should be declared external in theroutine from which mrwe_AddAppleEvent is called.
lresult is a LOGICAL value indicating whether the responseroutine was installed. If lresult=.TRUE., the routine wasinstalled properly. If lresult=.FALSE., the response was notinstalled because Apple Events are not supported by System 6.
For example, a routine that handles Print Document events could be installed with thefollowing call, where PrintDoc is the name of a function that will be called every timethe 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. Fora text event, it is a text string. The INTEGER value that your function should return is anerror code. It should return 0 if everything went well, or one of the error codes shown inTable 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 sendeither an Open Application event, an Open Document event, or a Print Document event.
178 The Macintosh Runtime Window Environment
Fortran User Guide
The following table shows several methods you can use to launch an application and thecorresponding Apple Event your application will receive:
Method of launch Apple Events received
Double-click the application icon or single-click it and choose Open from the File menu.
An Open Application event.
Double-click a document icon. An Open Document event, if successful. Thecreator of the document must match that of theapplication (Mrwe by default). Also, if there ismore than one application with the same creator,the application that is launched may not be the oneyou expect.
Select the application icon and the icons ofone or more documents, then double click onany selected icon or choose Open in the Filemenu.
An Open Document event for each documentwhose creator matches the application’s creator.
Select the icons of one or more documents,then drag them to the application icon.
An Open Document event for each document.
Select the application icon and the icons ofone or more documents, then choose Print inthe File menu.
A Print Document event for each document whosecreator matches the application’s creator.Immediately after the Print Document events, aQuit Application event will be received.
Launch the application from anotherapplication, like MPW.
Probably an Open Application event, although itdepends on the application doing the launch.
Apple Events Received Upon LaunchTable 8-5
The Macintosh Runtime Window Environment 179
Fortran User Guide
Error Codes Returned from Apple Event Routines
Apple Event routines return an INTEGER error code. If the value returned is 0, no erroroccurred; if it is not 0, an error occurred either in sending the Apple Event, or in thetarget application receiving the event. Following is a list of error codes and theirmeanings:
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 anApple Event to an application that is not currently running, the preferredamount 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 extrainformation in the event could not be extracted properly.
-1712 No response from the target application within the limit of sevenseconds.
-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. Forexample, System 6 does not support either Apple Events or usingmrwe_LaunchApp to launch other applications.
Error Codes for Apple EventsTable 8-6
Other Examples of Apple Events
Following are some additional examples of common events you might wish to transmitbetween applications:
Sending a request to the Finder
If you are running lengthy processes overnight or over the weekend, you may want toturn off your machine after all processes are completed. To do this, simply send theFinder a Shut Down Apple Event. This will turn off the computer if the Shut Down item inthe Finder's Special menu can turn off the system. When sending an Apple Event to theFinder, 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 withthe following statement:
180 The Macintosh Runtime Window Environment
Fortran User Guide
ires = mrwe_SendAE('FNDR','shut',0,'process=HD:System Folder:Finder','')
The Macintosh Runtime Window Environment 181
Fortran User Guide
Using other standard Apple Events
To cause another application (which supports Apple Events) to open a particular file, youwould 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 routineto 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 processthe file in a certain way. When the second application finishes, it can send a signal eventback to the sender to indicate completion.
Another way to send messages is through text events. The class and eventID are notlimited to the examples shown in Table 8-4 earlier in this section. They can be defined asany four characters you choose to distinguish different events. Following is an exampleof how to send information through text events. The sending application would include:
CHARACTER*30 internalFileWRITE (internalFile,*) a,b,cires=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,typeCHARACTER*(*) internalFile.READ (internalFile,*) a,b,c
Scripting
Scripting refers to text commands that an application can interpret and execute. MPWand 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 anotherthat has a scripting language, allowing the scriptable application to be controlled. It is notenough for an application to have a scripting language; it must also accept the Do ScriptApple Event. HyperCard 2.1 and MPW 3.3 are the first versions of these applications thatsupport Do Script. An example of sending a scripting command to HyperCard is:
182 The Macintosh Runtime Window Environment
Fortran User Guide
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 isbecause 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 cannotrecognize. To learn more about Apple Events, consult Inside Macintosh VI , “AppleEvents Manager” (Chapter 6), and the Apple Events Registry, published by AppleComputer, Inc.
Creating Multiple Windows
You can easily open additional windows in MRWE. While the standard windowdescribed at the beginning of this chapter shows characters in the standard input andoutput units, additional windows can show characters written to other units. Byspecifying ACCESS="window" in an OPEN statement, you open a window connected to theunit specified in the OPEN statement. Any read or write functions associated with that unitwill appear in a window. The ACCESS specifier can be expressed in the following threeways:
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 shouldbe expressed as positive integers.
top_edge and left_edge define the distance in pixels from thetop of the screen to the top of the window and from the left edgeof the screen to the left edge of the window, respectively. Botharguments are expressed as signed integers (either positive ornegative).
The following is a simple example of how to use the OPEN statement to create anadditional 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 sizewill be 200 pixels tall and 360 pixels wide. Since the location of the window is notspecified, the window will open using the MRWE default for window location. The
The Macintosh Runtime Window Environment 183
Fortran User Guide
second line writes the statement to the window. The READ statement in the third line willfunction 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 closethe window.
Showing Alert Messages
Macintosh applications often announce messages when a problem occurs by showing anAlert dialog box:
Show Alert Box ExampleFigure 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 thebutton that dismisses the Alert.
message is a CHARACTER string containing the text of the messageto be displayed.
Following are the possible values of the button argument and the corresponding buttonsthat 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” ButtonsTable 8-7
184 The Macintosh Runtime Window Environment
Fortran User Guide
The SetPrefs Tool
The MRWE interface to your Fortran program can be easily customized to meet yourneeds. The runtime attributes that you can specify include text characteristics, memoryrequirements, and how the application behaves when it quits. Included with AbsoftFortran 90/95 is the MPW tool SetPrefs, which lets you set preferences for runtimebehavior. Like other MPW tools, SetPrefs can be used either through a Commando dialogbox (see figure 8-7) or from the Worksheet command line. An example of invokingSetPrefs 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 aFortran PAUSE statement before it quits and will set its minimum memory requirementto 1000 kilobytes.
To access SetPrefs using the Commando interface, enter:
SetPrefs… (Note: Press Option-; to display …)
The following dialog box will appear:
SetPrefs Dialog BoxFigure 8-7
Below is a brief description of the options that are available to you within the SetPrefsTool. Options are grouped according to the way they appear in the SetPrefs dialog boxand are followed by the appropriate command line arguments.
The Macintosh Runtime Window Environment 185
Fortran User Guide
Applications to affect
Before you can choose any customization options in the dialog box, you must identifythe applications whose attributes will be affected. You can select either all futureapplications, 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 futureapplications 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 chooseone or more applications. The attributes that you select will apply to theseapplications when you click the Setprefs button.
End of execution
These options control the actions of the MRWE window before the application stopsexecuting.
Pause (-pause)
Click the checkbox if you want MRWE to pause after the program ends, allowingyou 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, textwill not be saved. If this option is prompt, a dialog will ask whether text should besaved. To automatically save text without a prompt, use always.
Window characteristics
These options affect only the standard MRWE window, not windows opened with theACCESS=“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 ofthe 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 aclose box, clicking it causes the program to stop.
186 The Macintosh Runtime Window Environment
Fortran User Guide
Window Size (-windowsize normal|maximize)
When MRWE starts, this specifies the size of the window. If the normal isselected, the window is the default size. If maximize is selected, the window ismaximized.
Text characteristics
These options control the appearance of text characters in the window. You mayprefer a text style different than the default for easier reading. Also, the text style ofthe 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 defaultstate is on.
Memory requirements
These options set the application’s memory requirements, which are shown in the GetInfo dialog box in the Finder.
Preferred (-sizepref KiloBytes)
Number of kilobytes of memory the program initially asks the system for. In theFinder's Get Info dialog box, this is the “Suggested size” and will initially be usedfor the “Current size”, although you can change this.
The Macintosh Runtime Window Environment 187
Fortran User Guide
Minimum (-sizemin KiloBytes)
This is the minimum number of kilobytes required to run the application. Theapplication will not be launched if this minimum amount of memory is notavailable.
Timer interval
If you turn on the timer interval feature with the -N9 compiler option, your programwill be interrupted at timed intervals to check for Command-Period termination andto 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 MRWEwill let Fortran code process exclusively. After the interval has expired, MRWEwill allocate processing time to other active programs. By default, the interval isset at 30 (1/2 second).
File characteristics
All Macintosh files have two attributes identifying the application that created the fileand the type or format of information contained in the file. When you save the text inan MRWE window, it is saved by default as if MPW had created the file and the filecontains standard text. In some cases, you may want the file to have a differentcreator 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 openedwith a Fortran OPEN statement.]
Creator (-creator 4-chars)
Specify four characters to identify the application that created the file(s) savedfrom 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 wordprocessors or SimpleText.
189
Fortran User Guide
CHAPTER 9
Macintosh Programming
This chapter covers the broad topic of programming specifically for the Macintosh andcovers additional topics of interest such as interfacing Absoft Pro Fortran with otherlanguages, 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 Directorymenu 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 thecommand line for compiling as shown in Figure 9-1, and then pressing the Enter key. Allstandard output and diagnostic output when compiling the examples are routed to theWorksheet.
Selection of the command to compile an exampleFigure 9-1
To execute a compiled application or tool, type the name on a line in the Worksheet andpress Enter or launch an application by double-clicking its icon from the Finder.
190 Macintosh Programming
Fortran User Guide
USING THE MACINTOSH TOOLBOX
This section describes how to access the routines available in the Classic and the CarbonLibraries of the Macintosh toolbox. Not all Classic routines are available with the CarbonLibrary and many operations must be performed differently. In particular, with theCarbon Library you must use “accessor” functions to manipulate system data structures;you can no longer access the components directly. For a complete explanation of theentire Macintosh toolbox, refer to Inside Macintosh listed in the bibliography. Written byApple, Inside Macintosh is the definitive resource for Macintosh programming and isessential if you plan to use the toolbox directly.
The following short Fortran 90/95 example shows how to use the Macintosh toolbox. Itdraws a diagonal line and then an oval inside of a box frame in the current window. Codefrom this example will be used throughout this section to demonstrate various issues.
PROGRAM Sample
USE WINDOWS
TYPE (Rect) :: rTYPE( WindowRecord) :: frontPOINTER(p_front, front)
p_front = FrontWindow()CALL SetPort(p_front)
CALL MoveTo(0_2, 0_2) ! x = 0 y = 0CALL LineTo(50_2, 25_2) ! x = 50 y = 25
r%top = 25r%left = 50r%bottom = 75r%right = 150CALL FrameRect(r)CALL PaintOval(r)
PAUSEEND
This example uses Fortran 90/95 derived types. The TYPE statements declare therectangle type r and the window type front. The actual types are defined in the includefiles. The PAUSE statement keeps the graphics from disappearing at the end of theprogram.
The same example in FORTRAN 77:
GLOBAL DEFINE INCLUDE "Windows.inc"END
PROGRAM Sample
RECORD /Rect/ rRECORD /WindowRecord/ front
Macintosh Programming 191
Fortran User Guide
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 = 0CALL LineTo(VAL2(50), VAL2(25)) ! x = 50 y = 25
r.top = 25r.left = 50r.bottom = 75r.right = 150CALL FrameRect(r)CALL PaintOval(r)
PAUSEEND
This example uses two special features of Absoft Fortran 77. First, GLOBAL DEFINEallows STRUCTURE, PARAMETER, INLINE, and EXTERNAL definitions from the INCLUDE filesto apply to all program units within a source file, reducing compile time because the filesare read only once. Second, the RECORD statement declares a rectangle structure r and awindow structure front. The actual structures are defined in the include files. The PAUSEstatement 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 Fortran90/95 to interface with the Macintosh toolbox. These files contain Fortran 90/95declarations for every routine and most of the structures, types, and constants defined inInside Macintosh, volumes I to VI. The files are named after the Macintosh managers towhich they refer; they are the same as the chapter titles in Inside Macintosh. The includefiles for Fortran 90/95 have been implemented as modules. Quickdraw.inc containssource code for the module QUICKDRAW.
All of the include files have been pre-compiled. For each .inc file there exists acorresponding .mod file that contains the compiled module code. To useQUICKDRAW.mod, pass the compiler the -macModFiles option, and employ thefollowing 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 compiledmodules.
How Absoft Fortran 77 Interfaces with the Toolbox
A group of FORTRAN 77 include files with the file extension .inc allows AbsoftFortran 77 to interface with the Macintosh toolbox. These files contain FORTRAN 77declarations for every routine and most of the structures, types, and constants defined in
192 Macintosh Programming
Fortran User Guide
Inside Macintosh, volumes I to VI. The files are named after the Macintosh managers towhich they refer;; they are the same as the chapter titles in Inside Macintosh. To includeone of these files, use a statement such as:
INCLUDE "Quickdraw.inc"
This INCLUDE statement will define all the Quickdraw information for a single programunit. To speed compilation and to define the same information for all program unitswithin a file, place the INCLUDE statement in a GLOBAL DEFINE block at the top of thefile:
GLOBAL DEFINE INCLUDE "Quickdraw.inc"END
There are many dependencies between the include files. As a convenience, all of thetoolbox INCLUDE files contain conditional compilation directives which willautomatically include the required files. So, although Quickdraw.inc requiresTypes.inc for certain structure definitions, it is not necessary to explicitly include it. Forexample:
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:F90Includesfolder. This folder contains both the .inc and the .mod files. The environment variable{F90Includes} is defined to reference this folder. You must use the -macModFilesoption 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 Macintoshtoolbox modules.
The FORTRAN 77 .inc interface files are located in the {MPW}Interfaces:Fincludesfolder. The environment variable {FIncludes} is defined to reference this folder.Interface files are accessed using the INCLUDE statement which first searches for the filein the current folder, next, in any folders specified with the -I compiler option, andfinally, in any folders specified with the {FIncludes} variable. See the chapter TheFORTRAN 77 Program in the FORTRAN 77 Language Reference Manual for detailson using the INCLUDE statement. See the chapter Using the Compiler in this manual for adiscussion of the -I compiler option.
Macintosh Programming 193
Fortran User Guide
If, for any reason, you want to move the INCLUDE files to another directory, you mustinform 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 environmentvariable is set every time MPW is launched.
Set FIncludes pathExport FIncludes
Passing Arguments
By language definition, Fortran passes all arguments and receives all dummy argumentsby reference. Absoft FORTRAN 77 and Fortran 90/95 can also pass arguments by valueusing the VAL() function and can receive dummy arguments by value using the VALUEstatement.
Standard FORTRAN 77 and Fortran 90/95 pass all arguments by reference. This meansthat 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 asto use the value passed. Other languages, such as C and Pascal, allow a choice of passingby reference or passing by value. Passing by value is one way communication. A copy iscreated of the argument and passed to the subprogram. This copy may be used andmodified but the actual argument is not changed.
To assist you with calling the toolbox from Fortran 90/95, Absoft Pro Fortran providesfunction interface blocks for each toolbox routine. The INTERFACE for MoveTo, found inQuickdraw.inc, is defined as follows:
INTERFACESUBROUTINE MoveTo( &
& h, && v)
INTEGER*2, VALUE :: hINTEGER*2, VALUE :: vEND SUBROUTINE MoveToEND INTERFACE
!DIR$ NAME(MOVETO="MoveTo")
Interfaces provide compile time argument type checking. If you call MoveTo with thewrong number of arguments or the type of either of the arguments is not INTEGER*2 thecompiler will issue an error. The interface also specifies that both arguments are passedby value. The compiler will automatically pass by value all arguments declared in aninterface as VALUE. This overrides the default Fortran 90/95 pass by referencemechanism. The !DIR$ NAME directive allows Fortran 90/95 to call mixed case routinessuch as MoveTo. By default the Fortran 90/95 compiler folds all names to uppercase.
194 Macintosh Programming
Fortran User Guide
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 referenceis simple because it is the standard Fortran convention. Passing by value requires the useof INTERFACE blocks in Fortran 90/95, or the appropriately sized VAL() function inFORTRAN 77. To determine the correct argument order and type, refer to InsideMacintosh and to the .inc files containing the routines you want to call. The followingFortran 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. Inparticular, 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 sectionFortran Data Types in Pascal later in this chapter for a table of Fortran and Pascal datatype compatibility. Passing more complex parameter types is discussed later in thischapter.
All pointers are 32 bits and must be declared as INTEGER*4 values or as POINTERs andpassed as arguments with the VAL4 function. These calls pass a pointer to the SetPortroutine in the toolbox:
INTEGER*4 p_frontCALL SetPort(p_front)
TYPE(WindowRecord) :: front ! Fortran 90/95POINTER(p_front, front)CALL SetPort(p_front)
RECORD /WindowRecord/ front ! FORTRAN 77POINTER(p_front, front)CALL SetPort(VAL4(p_front))
RECORD /WindowRecord/ front ! FORTRAN 77POINTER(p_front, front)CALL SetPort(front)
Newer versions of the Apple Inside Macintosh documentation use the C programminglanguage to describe the interface to the toolbox routines. Absoft Pro Fortran is designedto interface directly to the C programming language enabling Fortran programs to calltoolbox routines with the only requirement being careful attention to argument datatypes.
Macintosh Programming 195
Fortran User Guide
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 undeclaredvariables, thereby forcing explicit declaration of all variables used. Placing this statementat the beginning of each program unit is the easiest way to avoid difficulties due toundeclared or misspelled variable names. The following code fragments are examples ofusing the IMPLICIT NONE statement:
SUBROUTINE asub ! Fortran 90/95USE QUICKDRAWIMPLICIT NONEINTEGER x,y
x = 175y = 35CALL MoveTo(x, y)RETURNEND
GLOBAL DEFINE ! FORTRAN 77 INCLUDE "Quickdraw.inc"END
SUBROUTINE asubIMPLICIT NONEINTEGER*4 x,y
x = 175y = 35CALL MoveTo(VAL2(x), VAL2(y))RETURNEND
Details about the Absoft Fortran 77 implementation of IMPLICIT statement can be foundin the Specification and DATA Statements chapter of the FORTRAN 77 LanguageReference 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 listedbelow.
If a program is an application (the default), with or without MRWE, InitFApp.o calls noinitialization routines since the Carbon Library performs all initialization.
196 Macintosh Programming
Fortran User Guide
Using MRWE and the Toolbox
MRWE provides a Macintosh-style interface for generic Fortran programs and is notintended to be used in conjunction with programs that make extensive use of theMacintosh toolbox. Programs that have their own event loop or control their ownwindows will generally not use MRWE.
The MRWE example programs, however, demonstrate how MRWE may be used alongwith a custom window. In fact, some internal MRWE routines are called for the printingand saving of text.
Examples of complete programs that use the Macintosh toolbox and do not use MRWEare Snowflake.f90 and Snowflake.f which have their own event loops and controltheir own windows and menus.
Although the MRWE window grafport may be used for toolbox output, a text edit fieldcovers the entire window contents and is updated, thus erasing the grafport, during moststandard output or standard input.
Using STRUCTUREs and RECORDs with Toolbox
Here is an example of the PenState Pascal record, defined as:
TYPE PenState = RECORDpnLoc: 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 PenStateSEQUENCE 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 withthe toolbox for older 68000 based computers. PowerPC programs normally require dataelements to be aligned on natural boundaries, which occasionally requires padding
Macintosh Programming 197
Fortran User Guide
between structure elements to ensure proper alignment. The Absoft Pro Fortran compilersperform this padding by default so that programs will execute with optimumperformance. However, structures used by toolbox routines are exceptions to this rulesince 68000 programs running under emulation may also use them. Therefore, allstructures passed to and returned from toolbox routines must be packed. All of theINCLUDE files provided with the compiler contain compiler directives to ensure thatstructures 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%hWRITE(*,*) 'Vertical coordinate of pen = ', state%pnLoc%vEND
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.hWRITE(*,*) 'Vertical coordinate of pen = ', state.pnLoc.vEND
Passing the Toolbox a Pointer to a Fortran Routine
Certain toolbox routines require pointers to other routines as parameters. These may beroutines that you write to customize a standard toolbox feature or they may be handlersfor events that you wish to process asynchronously. The routine may be a PowerPCroutine or a 68000 routine. To accommodate this complexity, the toolbox uses amechanism called a Universal Procedure Pointer that communicates to the Mixed ModeManager the type of routine that you are using.
NOTE: A Universal Procedure Pointer is not required to call a toolboxroutine. It is only used when the toolbox routine will be making callsback to your routines.
198 Macintosh Programming
Fortran User Guide
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), thenumber of arguments in the parameter list, and the sizes of those arguments. UniversalProcedure Pointers and the Mixed Mode Manager are completely described in thedocument: Inside Macintosh: PowerPC System Software, but it is not necessary tocompletely understand the mechanism to use it. The following discussion and examplesshould provide all of the information necessary to use these facilities for normalpurposes.
The Absoft Pro Fortran compilation system provides a function called BuildDescriptorwhich creates a Universal Procedure Pointer descriptor and returns a pointer to it. Thesource code to this routine is also provided as BuildDescriptor.f. The constants anddeclarations for using BuildDescriptor are provided in the MixedMode.inc INCLUDE files.The Fortran 90/95 module information for BuildDescriptor is provided in the moduleABSOFT_MIXEDMODE.
UPP = BuildDescriptor(routine,convention,result,count,arguments)
where: UPP is a pointer to a Universal Procedure Pointer descriptor andshould be declared as an INTEGER variable.
routine is the address of the routine and must be declared in anEXTERNAL statement before appearing in the argument list to theBuildDescriptor function.
convention is an INTEGER argument describing the callingconvention type and is usually stated as kPascalStackBasedwhich describes PowerPC routines as well as the 68000 toolboxcalling conventions.
result is an INTEGER argument which indicates the size of theresult argument and must be one of the following: 0, 1, 2, or 4.
count is an INTEGER argument which indicates the number ofarguments to the routine.
args is an INTEGER array of at least count elements. The arraycontains the sizes of each argument to the routine and must be oneof 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 filterroutine to the ModalDialog toolbox routine. In Fortran 90/95:
USE MIXEDMODEUSE ABSOFT_MIXEDMODE
Integer (kind=4) :: args(2)Integer (kind=2) :: hit
Macintosh Programming 199
Fortran User Guide
Integer (kind=4) :: filter_UPPExternal filter
arg(1) = 4 ! size of pointer to dialog recordarg(2) = 2 ! size of dialog itemfilter_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 hitinteger*4 filter_UPPexternal filter
arg(1) = 4 ! size of pointer to dialog recordarg(2) = 2 ! size of dialog itemfilter_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 necessaryto create, respond to, or dispose of the dialog. They are intended onlyto show the necessary calls to manage the Universal Procedure Pointerassociated with a custom filter routine.
DisposeRoutineDescriptor must eventually be called to dispose of the memory thatwas allocated by BuildDescriptor, but only after the descriptor has been used. It maybe more efficient to allocate Universal Procedure Pointer descriptors once at thebeginning of a program for those routines that will be commonly used and then place theaddresses of the descriptors in a COMMON block. Universal Procedure Pointers are usedwhenever 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 anew location and pointers referencing data in those blocks will be left “dangling”, orpointing 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 amaster pointer that exists for each moveable block. When the block is moved, theMemory Manager properly updates its master pointer and all handles are still validbecause the master pointer has not moved. In other words, handles are pointers topointers.
200 Macintosh Programming
Fortran User Guide
Master Pointer
•••
•••
Master Pointer
Master Pointer
Master PointerMemory
Handle ������������������������������������������������������������������������������������������������������������������������������������������������������������������������
������������������������������������������������������������������������������������������������������������������������������������������������������������������������
Handle
A handle points to a pointer to a memory blockFigure 9-2
Handles are dealt with in much the same manner as pointers. This section of code fromthe SetCurs.f example program, gets a handle to a cursor, dereferences it, and passesthe dereferenced cursor record to SetCursor.
INTEGER*2 cTypeTYPE(Cursor) :: theCursor ! use a cursor structurePOINTER(p_theCursor, theCursor) ! pointer to theCursorPOINTER(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 secondsEND DO
Macintosh Programming 201
Fortran User Guide
Accessing the Quickdraw Globals
A copy of the structure that contains the Quickdraw globals is placed in the predefinedCOMMON block absoft_QD during program startup. The structure is declared in theINCLUDE file quickdraw.inc as follows:
TYPE QDGlobalsSEQUENCE 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) :: thePortENDTYPE QDGlobals
The following example shows how to use it to determine how large the screen is that theprogramming is running on:
USE QUICKDRAW
INTEGER height, width
TYPE(QDGlobals) :: qdCOMMON /absoft_QD/ qd
height = qd%screenBits%bounds%bottomwidth = qd%screenBits%bounds%right
NOTE: Access to the Quickdraw globals from within a Carbon application is performedwith “accessor” functions. See the MRWE source code for examples.
Apple Events
Apple events provide a mechanism whereby a program can receive and process messagesfrom the Finder and from other applications. Apple provides over 100 pages ofdocumentation on the Apple Event Manager in Inside Macintosh, Volume VI and it isbeyond the scope of this manual to attempt to duplicate that effort here. However, thissection will provide a basic understanding of Apple events and sufficient information torespond 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 interestare:
isHighLevelEventAwarelocalAndRemoteHLEvents
202 Macintosh Programming
Fortran User Guide
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 theEvent Manager by making a toolbox call such as WaitNextEvent. The program thenmakes a call to the toolbox routine AEProcessAppleEvent with the address of the eventrecord. The Apple Event Manager then dispatches the event to the individual handlerroutines within the program. However, the program must first register the events that itwill take responsibility for with the Apple Event Manager and supply the addresses of theroutines that will handle the events. This is accomplished with the AEInstallhandlertoolbox call that takes, as one of its arguments, a Universal Procedure Pointer thatspecifies the routine address. Universal Procedure Pointers were described earlier in thischapter in the section Passing the Toolbox a Pointer to a Fortran Routine:
Macintosh Programming 203
Fortran User Guide
USE EVENTSUSE APPLEEVENTSUSE MIXEDMODEUSE ABSOFT_MIXEDMODEUSE EPPC
integer oapp; external oapp ! open application routineinteger odoc; external odoc ! open document routineinteger pdoc; external pdoc ! print document routineinteger quit; external quit ! quit application routine
integer oapp_UPP ! oapp Universal Procedure Pointerinteger odoc_UPP ! odoc Universal Procedure Pointerinteger pdoc_UPP ! pdoc Universal Procedure Pointerinteger quit_UPP ! quit Universal Procedure Pointer
integer args(3)integer*2 OSErr
args(1) = 4 ! AppleEvent recordargs(2) = 4 ! reply recordargs(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 typeof event that the Event Manager will report is a kHighLevelEvent, defined in theEPPC.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 selectend do
204 Macintosh Programming
Fortran User Guide
The AEProcessAppleEvent toolbox call will invoke the appropriate handler routine toprocess 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 ofthese routines will have the same basic format. In Fortran 90/95:
integer*2 function oapp(event,reply,RefCon)
type(AEDesc) :: eventtype(AEDesc) :: replyinteger RefConvalue RefCon.oapp = 0 ! non-zero return value indicates an error
end
In FORTRAN 77:
integer*2 function oapp(event,reply,RefCon)
record /AEDesc/ eventrecord /AEDesc/ replyinteger RefConvalue 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 QuitApplication handler will call the normal quit or exit routines of the program andobviously never return. An Open Document handler will first call the toolbox routineAEGetParamDesc 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 routinewill then cycle through the list, calling AEGetNthPtr to obtain a pointer to the filespecification of each document. The file specifications are passed to the program’s actualopen document routine (called OpenDocument in the example below). After all of thedocuments have been processed, AEDisposeDesc disposes of the Apple event descriptor.The following function represents a minimum Open Document handler routine:
Macintosh Programming 205
Fortran User Guide
integer*2 function odoc(event,reply,RefCon)
use FILESuse APPLEEVENTS
implicit none
type(AEDesc) :: eventtype(AEDesc) :: replyinteger RefConvalue RefCon
integer*2 OSErrtype(AEDesc) :: docList
integer keywd, returnedTypetype(FSSpec) :: fileinteger 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 theOpenDocument reference with a call to a PrintDocument routine.
206 Macintosh Programming
Fortran User Guide
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 AbsoftTechnical Support. They include demonstrations of graphics, printing, access to theMacintosh serial ports, and standard user interface techniques.
Many of the example programs contain calls to the Macintosh toolbox. Some of theexamples use the Macintosh Runtime Window Environment (MRWE) for standard inputand output along with toolbox calls to create graphics. There may be additional exampleprograms in the FExamples folder that are not listed here. Read the comments in theexample programs themselves for more information.
Example program DescriptionARGSt 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
Color 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 assemblylanguage. Although Fortran programs can call C and Pascal subroutines easily with just aCALL statement, the sections below should be read carefully to understand the differencesbetween argument and data types. The interfaces to C detailed below apply specifically toAbsoft C/C++ and should be similar for MPW compilers available from other vendors.For information about linking C and Pascal, consult the manuals accompanying thosecompilers.
Macintosh Programming 207
Fortran User Guide
Interfacing with C
Absoft Pro Fortran is designed to be fully compatible with the implementation of thestandard C language on the Macintosh. The linker can be used to freely link C moduleswith Fortran main programs and vice versa. However, some precautions must be taken toensure proper interfacing. Data types in arguments and results must be equivalent. Thecase of global symbols on the Macintosh is significant. The symbolic names of externalprocedure 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 storageallocated by the corresponding Fortran declaration.
There are additional precautions when passing Fortran strings to C routines. See thesection 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 Cprogramming language. Therefore, a Fortran routine may be called from C without beingdeclared in the C program and vice versa, if the routine returns all results in parameters.
208 Macintosh Programming
Fortran User Guide
Otherwise, the function must be typed compatibly in both program units. In addition, caremust be taken to pass compatible parameter types between the languages. Refer to thetable above.
Reference parameters
All Fortran arguments to routines are passed by reference, which means pointers to thedata 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 pointvalues may be passed by reference. Consider the following example:
SUBROUTINE SUB(a_dummy,i_dummy)REAL*4 a_dummyINTEGER*4 i_dummy
WRITE (*,*) 'The arguments are ',a_dummy, ' and ', i_dummyRETURNEND
The above subroutine is called from Fortran using the CALL statement:
a_actual = 3.3i_actual = 9CALL SUB(a_actual, i_actual)END
However, to call the subroutine from C, the function reference must explicitly passpointers 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 Fortransubroutine with an assignment statement or an I/O statement.
When calling a C function from Fortran with a reference parameter, the C parameters aredeclared as pointers to the data type and the Fortran parameters are passed normally:
PROGRAM convert_to_radiansWRITE (*,*) 'Enter degrees:'READ (*,*) cCALL C_RAD(c)WRITE (*,*) 'Equal to ',c,' radians'END
Macintosh Programming 209
Fortran User Guide
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, thesefunctions may be used to pass a value to a C function. The following is an example ofpassing a 4-byte integer:
WRITE (*,*) 'Enter an integer:'READ (*,*) iCALL 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. Thearguments 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 theonly Fortran data type that cannot be passed by value is CHARACTER.
210 Macintosh Programming
Fortran User Guide
Array Parameters
One-dimensional arrays can be passed freely back and forth as both languageimplementations pass arrays by reference. However, since C and Fortran use differentrow/column ordering, multi-dimensional arrays cannot be easily passed and indexedbetween 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, orDOUBLE. All other data types must be returned in reference parameters. The following areexamples 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 callcINTEGER*4 CMAX, A, B
WRITE (*,*) 'Enter two numbers:'READ (*,*) A, BWRITE (*,*) 'The largest of', A, ' and', B, ' is ', CMAX(A,B)END
int CMAX (x,y)int *x,*y;{
return( (*x >= *y) ? *x : *y );}
Macintosh Programming 211
Fortran User Guide
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 fixedlength, 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 anull character. The following Fortran expression will properly pass the Fortran stringstring to the C routine CPRINT:
PROGRAM cstringcallcharacter*255 stringstring = '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 werenot 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 Clanguage 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 thebeginning forms the names of the functions that can be called.
212 Macintosh Programming
Fortran User Guide
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 prependingthe characters “_C” to the name of the COMMON block. The elements of the COMMON blockcan 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 beenexplicitly identified. The section Setting Up Inter-Language Calls later in this chapterexplains how to do this.
Macintosh Programming 213
Fortran User Guide
Fortran Data Types in Pascal
Declarations for Fortran data types and the equivalent declarations in Pascal are asfollows:
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;Varc: Comp_type
COMPLEX*16 d Type Compd_type = Record x: double; y: double; End;Vard: Compd_type
The storage allocated by the Pascal language declarations will be identical to the storageallocated by the corresponding Fortran declaration. Be sure to use equivalent types whenpassing parameters between languages or your results will be invalid.
There are additional cautions when passing Fortran strings to Pascal routines. See thesection 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 Fortranevaluates function parameters from right-to-left while Pascal evaluates left-to-right. Thiswould cause the values on the stack upon entry to be misinterpreted. In addition, Pascalexpects function results to be returned on the stack while Fortran returns them inregisters. Obviously, in order for a Fortran program to communicate with a Pascalprogram or vice versa, the programs must know that they are interfacing with the otherlanguages so adjustments may be made. The correct declarations are given below.
214 Macintosh Programming
Fortran User Guide
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 toright, while EXTERNAL tells the compiler that the routine is declared in a differentprogram unit. The Fortran declarations have the following format for Pascal functionsand procedures, respectively:
type p_funcPASCAL EXTERNAL p_func
PASCAL EXTERNAL p_proc
The routines in Pascal must be declared in a special format known as a unit. A Pascal unitis similar to a program, except that it is not executable by itself. This form is necessarybecause if the Pascal source file has a PROGRAM statement, it will become the mainprogram, and the calls from Fortran will be ignored. Units are declared in Pascal usingthe following form:
UNIT unitname;
INTERFACEFunction p_func (parameters) : type;Procedure p_proc (parameters);
IMPLEMENTATIONFunction p_func;Begin . . .End;
Procedure p_proc;Begin . . .End;
END.
Anything (constants, types, variables, routines) declared in the INTERFACE section isavailable to all outside programs which link to the unit, and anything declared in theIMPLEMENTATION section is accessible only within the unit. You can see this from howthe routine headers are defined in the INTERFACE section, and routine bodies in theIMPLEMENTATION section. The parameter lists and function result types are not repeatedin the IMPLEMENTATION section.
Once these declarations are complete, the Pascal routines can be called in the samemanner as Fortran routines, with functions returning values to the calling point withinexpressions, and procedures being accessed via the CALL statement. It can be seen fromthis that Pascal functions are analogous to Fortran functions and Pascal procedures to
Macintosh Programming 215
Fortran User Guide
Fortran subroutines. For the routines declared above, these calls from Fortran wouldsuffice:
type p_funcPASCAL EXTERNAL p_func
PASCAL EXTERNAL p_proc
type aa = 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 todeclare the routine as Pascal inside the Fortran program. This is done by placing thestatement 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 anyexternal functions written in Pascal. The Pascal directive EXTERNAL is used to declare theroutines 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 anexternal C routine with the C and EXTERNAL directives. The C directive causes Pascal touse the C/Fortran calling conventions, evaluating parameters from right to left, andreturning function results in the registers expected by Absoft Fortran 90/95. TheEXTERNAL directive makes the program look externally for the routine declaration. Thedirectives 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 aboveif the PASCAL directive was removed from the Fortran code. Either of these two methodsallows the Fortran routines to be called in a normal fashion from Pascal. Note that all thePascal parameters are declared with the keyword VAR. The reason for this will beexplained in the next section.
Passing Values Between Pascal and Fortran
In Fortran, all arguments to subroutines and functions are passed by reference. Thismeans that a pointer to the data item is passed rather than the actual data. Since Pascalprovides a choice between reference and value passing, passing data between the two
216 Macintosh Programming
Fortran User Guide
languages requires careful determination of the proper parameter types. See the sectionFortran 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 bedeclared as by reference. This is done using the VAR keyword. Note that both floatingpoint and integer values may be passed. For instance, here are two versions of asubroutine 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+YA = S/2 A = S/2RETURN RETURNEND 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 nowbehaves exactly like a Pascal routine. However, both versions may be called from Pascalsimply be varying their declarations as follows (taking care to use VAR for all parameterdefinitions):
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;
Beginx := 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 subroutinesince they are called by reference.
Macintosh Programming 217
Fortran User Guide
Value parameters
Absoft Pro Fortran provides the intrinsic function %VAL for passing value parameters toPascal. The following is an example of passing a 4-byte integer:
PASCAL EXTERNAL p_proc
i = 10CALL p_proc(%VAL(i))END
UNIT pfcall;
INTERFACEProcedure p_proc(n : longint);
IMPLEMENTATIONProcedure 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;
INTERFACEProcedure fortran_sub(n : longint); C; EXTERNAL;
IMPLEMENTATIONProcedure 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 typecannot be passed by value.
218 Macintosh Programming
Fortran User Guide
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 ofFortran 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 bedefined specially before being called. The following are examples of passing functionresults between Fortran and Pascal.
A call to Pascal from Fortran
REAL*4 in_to_cmPASCAL EXTERNAL in_to_cm
WRITE(*,*) 'Enter number of inches:'READ(*,*) BWRITE(*,*) B, ' inches = ', in_to_cm(B), ' centimeters.'END
UNIT pfcall;INTERFACE
Function in_to_cm(VAR inches : Real) : Real;
IMPLEMENTATIONFunction 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;
Varx : Real;
Beginx := 3.14159 / 3.0; (* 60 degrees in radians *)Writeln('Sine of ', x, ' = ', fsin1(x));Writeln('Sine of ', x, ' = ', fsin2(x));
End.
Macintosh Programming 219
Fortran User Guide
REAL*4 FUNCTION fsin1(A)REAL*4 Afsin1 = SIN(A)RETURNEND
PASCAL REAL*4 FUNCTION fsin2(A)REAL*4 Afsin2 = SIN(A)RETURNEND
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 bytecontaining the length of the string to the beginning of it. This example demonstrates theproper format:
PROGRAM pstringcallCHARACTER*50 str50PASCAL EXTERNAL PPrintstr50 = CHAR(12)//'twelve chars'CALL PPrint(str50)END
UNIT pfcall;INTERFACE
Type Str20 = string[20];Procedure PPrint (VAR astr : Str20);
IMPLEMENTATIONProcedure PPrint;Begin Writeln(astr, ' is ', Length(astr), ' characters long.');End;
End.
This example will print “twelve chars is 12 characters long.” Without the lengthbyte, Pascal will use the first character as the length and produce erroneous andunpredictable results.
Calling Fortran math routines
All of the Fortran intrinsic math functions which return values recognized by the Pascallanguage 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.
220 Macintosh Programming
Fortran User Guide
The names of the functions which can be called are formed by taking the intrinsicfunction 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;
VARa, sina : Real;
Begina := 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 inregisters r3-r10 or in the stack. The lengths of character arguments are passed as 32 bitintegers above the addresses. On entry to a Fortran procedure, the stack frame is definedas 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)) + 24length position = (n * 4 + (q-1) * 4) + 24
where: m = argument numbern = total argumentsq = character argument number
The Fortran Stack FrameFigure 9-3
Macintosh Programming 221
Fortran User Guide
Upon entry to a procedure, the addresses of the first eight arguments will be passed inregisters r3-r10 and the address of any additional argument will be passed in the stackframe. Space for locally saving the arguments passed in registers will have been allocatedin the stack frame. The length field is allocated only for CHARACTER argument types andimmediately follows the actual arguments in the stack.
Value arguments for all non-floating-point arguments except CHARACTER are passed inregisters (if there is enough space in registers r3-r10) or in the stack. Floating-pointvalue arguments are passed in registers f1-f13. Space in registers r3-r10 is skipped tocorrespond to arguments passed in floating-point registers. For example, if a procedurereference has three arguments passed by value and they are an integer, a double precisionvalue and another integer in that order, the first argument will be passed in r3, the secondin f1 and the third in r6.
Space for CHARACTER and derived type function results is passed as if it were an extraargument at the beginning of the argument list. For example, the following two calls areequivalent in respect to how arguments are passed to the external function or subroutine:
CHARACTER*10 funct, arg, resultEXTERNAL sub
result = funct(argument)CALL sub(result,argument)
Function Results
Absoft Fortran 90/95 returns all numeric and logical function results except derived typein the caller’s register r3 or in the registers f1 and f2 depending on the width and datatype of the result.
CHARACTER and derived type results are not returned in registers. The address of spacefor 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 designedfrom the “how to” viewpoint with Fortran in mind. For complete information about usingresources, see the “Resource Manager” chapter of Inside Macintosh.
A resource editor, such as ResEdit, available from APDA, is very useful for modifyingexisting resources or copying resources between files. The MPW tool Rez, included withAbsoft Fortran 90/95, is a resource compiler that creates new resources based on a textualresource description file. Rez is documented in Chapter 8 along with DeRez, a decompilerof resources that generates a resource description file.
By looking at existing resource description files in the FExamples folder and using DeRezto create new ones, much can be learned about the language syntax of resource
222 Macintosh Programming
Fortran User Guide
description files. The paragraphs below will show, by example, the most commonconstructs. For a complete description of the language, see the Macintosh Programmer’sWorkshop Manual. Examples are given below for adding ICON and SIZE resources toapplications. These are used by the Finder to determine the icon to use for an applicationand the amount of memory to set aside for an application.
Include Files
Every resource description file must include the file Types.r which defines standardMacintosh resources. It is located in the RIncludes folder. The following line placed incolumn 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 aunique icon for an application instead of the default application icon. The followingexample defines the ICN#, BNDL, and FREF resources. The resource FSMP can have anyname but must match the creator that is set with the -c type linker option. See thechapter “Finder Interface” in Inside Macintosh for details about how these resources areused 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"
}};
Macintosh Programming 223
Fortran User Guide
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 useMRWE by adding these resources to the MRWE.r file and rebuilding the MRWE library asdescribed in the Read Me file of the MRWE folder.
All applications that use MRWE have the following balloon help for its icon when shownin the Finder.
The help is simply defined in a ‘hfdr’ resource with ID -5696. This code is from theMRWE.r file in the FExamples:MRWE folder:
224 Macintosh Programming
Fortran User Guide
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 examinedto determine how much memory the application requires. The SIZE(-1) resource from thefile Snowflake.r is shown below and sets the minimum memory size to 48K and thepreferred to 64K. These are the values that appear in the Get Info… dialog box from theFinder. The other elements of the SIZE(-1) resource are listed in the types.r ResourceManager interface file and documented in the Event Manager chapter of InsideMacintosh, 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 theMRWE.r file and rebuilding the MRWE library as described in the Read Me file of theMRWE folder. By default, MRWE has a SIZE(-1) resource that specifies 384K for theminimum and preferred sizes for applications. This value may be increased for largeapplications that need more memory when using MultiFinder.
The minimum size can also be set from the Get Info… dialog. Any changes made in thisway will be lost, however, the next time the application is generated.
Macintosh Programming 225
Fortran User Guide
Compiling a Resource Description File
The following invocation of Rez, from the Snowflake.make file, compiles the resourcedescription 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 PowerPCbased Macintosh computers. The operation of the debugger is detailed in the nextchapter, Using the Fx Debugger. The following paragraphs describe the compileroptions and resources necessary to prepare a program for debugging.
NOTE: Only desktop applications, with or without MRWE, can be debuggedwith 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 toadd symbol and line number information to the object file. This option should be enabledfor each source file that you will want to have source code displayed while debugging. Itis not required for files that you are not interested in.
It is recommended that all optimization options be disabled while debugging. This isbecause the optimizers can greatly distort the appearance and order of execution of theindividual statements in your program. Code can be removed or added (for loopunrolling), variables may be removed or allocated to registers (making it impossible toexamine 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 usingthe commando dialog for the compiler, this will be done automatically. If you havecreated 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 thecharacters .FxSym appended to the end.
Size Resource
An application must have a SIZE resource with the canBackground flag set in order to bedebugged. See The SIZE(-1) Resource section earlier in this chapter.
226 Macintosh Programming
Fortran User Guide
PROFILING
The Absoft source-level debugger, Fx, is also used to gather profile information about anapplication. Profmt, a tool supplied with the compiler is used to display the profilestatistics in both tabular format and graphically. The operation of Fx and Profmt forprofiling is described in the next chapter, Using the Fx Debugger. The followingparagraphs describe the compiler options and resources necessary to prepare a programfor profiling.
NOTE: Only desktop applications, with or without MRWE, can be debuggedwith 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) directsthe compiler to add the symbol information to the object file necessary to profile anapplication. Enabling this option will allow the debugger to report the number of times aparticular 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 usingthe commando dialog for the compiler, this will be done automatically. If you havecreated 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 thecharacters .FxSym appended to the end.
Size Resource
An application must have a SIZE resource with the canBackground flag set in order to bedebugged. See The SIZE(-1) Resource section earlier in this chapter.
227
Fortran User Guide
CHAPTER 10
Using the Fx Debugger
INTRODUCTION TO FX
Fx is a multi-language, source-level symbolic debugger for the Macintosh PowerPCbased computers and is designed to meet the needs of both the casual and the professionalprogrammer alike. It provides standard debugging capabilities, such as breakpoints andvariable display, and includes advanced features like source language, context sensitive,expression analyzers, dynamic windows, and execution profiling. It fully supports AbsoftFortran 90/95, FORTRAN 77, C, and C++, as well as the Apple implementation of the Cprogramming language and the Apple PowerPC assembler.
A debugger is a fundamental programming tool that is used to achieve a specific end. Fxis 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 keysequences to remember. Fx commands do exactly what you expect them to. The depth ofdetail 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 willneed for effective debugging as quickly as possible. The following descriptions of theremaining 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 withsymbolic debugging information and start a debugging or profiling session. It alsodescribes how to set breakpoints, single step, examine variables, and quit thedebugger. Experienced programmers will find all the information they need in thissection.
• Debugging Concepts
This section is designed for the less experienced programmer and presents basicdebugging 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 adebugging session
• Fx Menus and Windows
This section discusses in detail the Fx menu commands and the windows that theycontrol. Every Fx command is described in this section.
228 Using the Fx Debugger
Fortran User Guide
• Profiling
This section describes how to compile and link your program for profiling, use Fx togather execution statistics, and how to use the information that is collected to analyzeprogram execution.
PREPARING FOR DEBUGGING
This section describes how to prepare your program for debugging with Fx and how tobegin a debugging session. It also introduces the use of breakpoints, single stepping, andexamining variables.
Source level debugging with Fx (or any debugger) requires that the symbolic informationcontained in the original source file be available to the debugger. Normally, thisinformation is used only by the compiler during the early stages of parsing and lexicalanalysis and then discarded after the object file has been created. Preparing a program fordebugging consists primarily of setting the required compiler and linker options to createa 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 Debugwith Fx checkbox in the main commando dialog) to direct the compiler to add symbol andline number information to the object file. This option must be enabled for each sourcefile that you will want to have the source code displayed for while debugging. It is notrequired for files that you are not interested in.
Using the Fx Debugger 229
Fortran User Guide
Figure 10-1Fortran compiler option
Use the -g option with Absoft’s C/C++ compiler (the Debug with Fx checkbox in thecommando dialog) to direct the compiler to add symbol and line number information tothe object file. This option must be enabled for each source file that you will want to havethe source code displayed for while debugging. It is not required for files that you are notinterested in.
Figure 10-2C compiler option
230 Using the Fx Debugger
Fortran User Guide
It is recommended that all optimization options be disabled while debugging. This isbecause the optimizers can greatly distort the appearance and order of execution of theindividual statements in your program. Code can be removed or added (for loopunrolling), variables may be removed or allocated to registers (making it impossible toexamine 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… commandodialog) must be added to the command line for the Absoft linker, lnk. If you are usingthe commando dialog for the compiler, this will be done automatically. If you havecreated a Build script, you should add the option to the command line for lnk.
Figure 10-3Linker option
The symbol file created by the linker with have the same name as the application with thecharacters .FxSYM appended to the end.
Size(-1) Resource
An application must have a SIZE(-1) resource with the canBackground flag set in orderto be debugged. The flag can be set with a resource editor such as ResEdit, or by usingthe resource compiler tool, Rez, that is provided in the MPW environment. An exampleSIZE resource is presented below:
resource 'SIZE' (-1) {dontSaveScreen,acceptSuspendResumeEvents,enableOptionSwitch,canBackground,multiFinderAware,backgroundAndForeground,dontGetFrontClicks,ignoreChildDiedEvents,not32BitCompatible,reserved,reserved,reserved,reserved,
Using the Fx Debugger 231
Fortran User Guide
reserved,reserved,reserved,* 64,* 48
};
System Folder Additions
Communication between Fx and the application being debugged is managed by abackground process called PowerMac Debug Services. It must be launched before Fx can beused — if it is not already running Fx will report an error. You should place it in theStartup Items folder inside the System Folder where it will always be available when youwant to begin a debugging session.
PowerMac Debug Services also requires the system extension, PPCTraceEnabler, in order toallow Fx to place the PowerPC chip into trace or single step mode. This extension is anintegral part of System 7.5 and later, but must be placed in the Extensions folder of theSystem Folder for System 7.1.
Note: The necessary files are normally placed in the required folders of the System Folderduring 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, chooseOpen… 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 initializationcode, and leave it ready for debugging at the first executable statement of the mainprogram.
232 Using the Fx Debugger
Fortran User Guide
You can execute statements one-at-a-time by selecting the Step Into or Step Overcommands from the Control menu. Step Into will follow subroutine calls and functionreferences, 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 asthough they were a single statement and return you to the point of the call. The Run Tocommand will execute all of the statements up to line currently selected in the sourcecode window.
Breakpoints are set by moving the cursor to the left of the vertical gray line in the sourcewindow where the line number display is maintained and clicking the mouse button. Theletter B will appear, indicating a breakpoint at that line number. Clearing a breakpoint isaccomplished by simply clicking the mouse button on any line number where abreakpoint is set. Also, breakpoints may be temporarily disabled without clearing themby clicking the mouse button on the letter B. The letter D will be displayed as long as thebreakpoint is disabled.
Holding down the Option key while setting a breakpoint brings up the breakpoint controldialog which allows you set skip counts and special conditions which must be met beforea breakpoint takes affect. Holding down the Option key while clicking on a line numberexecutes the Run To command in the Control menu.
Variables can be examined in several ways. The easiest method is to simply select asymbol 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 automaticallyinserted between the quotation marks. If the variable is a pointer, selecting Print * “” willdereference 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 anysymbol or address expression in the current procedure that you wish to examine. Whereasthe Print “” and Print * “” commands will only display variables in a format consistent withtheir 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 theassociated print commands, but continuously update the value display as you stepthrough the program.
Using the Fx Debugger 233
Fortran User Guide
DEBUGGING CONCEPTS
This section is intended for the less experienced programmer and presents basicdebugging concepts such as single stepping through programs and using breakpoints. Italso describes how to isolate problems in your program and get the most out of adebugging session
Getting Started
Before beginning this section, you should be familiar with the information presented inthe previous section, Preparing For Debugging. It describes how to compile and linkyour program and how to start a debugging session. After Fx has been launched and youhave opened the application for debugging, a source code window is displayed similar tothe one shown below:
Figure 10-4Source code window
Positioned at the top of this window are two pop-up menus — a file menu on the left anda procedure menu on the right. The file menu contains a list of all of the files that wereused to build the application and is available for easily accessing the various files theycomprise the source code to the program. Initially, Fx will only look for source files inthe folder where the application was launched. If the source code is maintained inmultiple folders, use the Add Path command in the File menu to add additional folders tothe 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 linenumber — the line number where the program is stopped.
234 Using the Fx Debugger
Fortran User Guide
The gray vertical line divides the text window into two sections. The section on the rightis the source code for the current procedure. Text, such as variable names and addressexpressions, can be selected in this window and displayed using one of the commandslike Print or Watch in the Actions menu. If a procedure name is selected, you can use theSet 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 Controlmenu will execute all of the statements up to the source code line currently selected in thewindow.
The section to the left of the gray vertical line shows the line number of every line in thesource file — comment, declaration, and executable. Executable statements are furtherdenoted with a small diamond to the far left indicating that a breakpoint (see below) maybe set on that line. The current line, the line where the program is stopped, is marked thecharacters: =>.
When the cursor or mouse pointer is moved into the region to the left of the gray verticalline it changes into a pointer with a larger diamond. This indicates that breakpoints maybe 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 ofthe next line. If the line contains more than one executable program statement, they areall executed as one. If a statement is continued across multiple lines, they are all treatedas 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 tofollow the procedure reference or to simply treat it as a single statement. If you arecertain that the procedure is correct, you can Step Over the reference and allow all of thestatements in it to execute as one. If, on the other hand, you are suspicious of the routinein question, you can choose to Step Into it, following the flow of execution. If you changeyour mind, the Return command in the Actions menu will execute all of the remainingstatements 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 programcontains many loops or loops that iterate many times. It is far more efficient to allow theprogram to execute normally until it reaches a point where you want to take a closer lookat exactly what it is doing. Breakpoints are the solution. A breakpoint is a location in aprogram, determined by you, where execution stops. You simply set a breakpoint at thelocation 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 thedebugger.
Using the Fx Debugger 235
Fortran User Guide
Setting a breakpoint with Fx is extremely easy — you just point to the line number withthe mouse and click the mouse button. Once a breakpoint has been set, the letter Breplaces the diamond, indicating that a breakpoint has been set on that line.
Figure 10-5Setting a breakpoint
To clear a breakpoint, you do exactly the same thing — point to a line number with abreakpoint set on it, click the mouse button, and the letter B is replaced with the originaldiamond.
Breakpoints may be temporarily disabled without removing them by clicking the mousebutton with the pointer positioned directly over the letter B itself — the letter B willchange to a D, indicating that the breakpoint is disabled. Disabled breakpoints are enabledagain by performing the same operation on the letter D.
To give you further control over execution, you can set more conditions than justreaching the line where the breakpoint is set before stopping execution. This is veryimportant if your program must execute the same statement many times before you areinterested in stopping it. Additional conditions are placed on breakpoints in thebreakpoint 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 breakpointindicator.
or:• Use the Breakpoints command in the Windows menu
236 Using the Fx Debugger
Fortran User Guide
If you use the Breakpoints command in the Windows menu, you double-click on thebreakpoint that you are interested in to bring up the breakpoint control dialog (seeBreakpoints 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 anaddress for assembly language. Skip Count determines the number of times that thisstatement must execute before stopping for the breakpoint. Condition is a logicalexpression 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 thefollowing 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 onthe 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 byclicking on the Disabled radio button.
The One Time check box causes the breakpoint to be removed the first time executionstops at the line it controls.
Displaying Variables
Fx displays information about program variables in a special window type called theSymbols window. The easiest way to open a Symbols window to display a variable is toselect the name of the variable in the source code window and issue the Print “” command
Using the Fx Debugger 237
Fortran User Guide
from the Actions menu. Fx inserts whatever is selected in the front-most window betweenthe 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 andvalues 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 aggregatesuch as an array, structure, record, union, class, etc., its value is printed as the aggregatetype enclosed in brackets: <array>, <struct>, <union>, etc. The elements of the variableare displayed by double-clicking in the value field. An additional pane, indicating thedata type of the variable, can be added to the left of the symbol name with the Typescommand in the View menu as shown here:
Figure 10-6Symbols window with a Type pane
The width of these panes can be adjusted as necessary by moving the mouse pointer tothe title row, placing it over one of the vertical lines (where the cursor will changeshape), 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 isalready displayed in the Symbols window, select its name and use the View As… commandin 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 displayformat.
The mouse, tab key, or arrow keys may be used to navigate through the list of variablesin a Symbols window. Holding down the Option key while pressing either the right or leftarrow keys will move to the next column rather than the next character. Holding downthe Option key while pressing either the up or down arrow keys will move to the first orlast column in the current row respectively. Holding down the shift key while pressingthe tab key will move to the previous variable.
If a symbol is an array, its value is printed as the string <array> as mentioned above.Double-clicking in the value field of an array opens a new Symbols window displayingthe individual array elements up to the limit specified in the Array Size field of the
238 Using the Fx Debugger
Fortran User Guide
Preferences… dialog which is found in the Edit menu (see the Preferences section). Thisis reasonable for small arrays of no more than 100 elements or so, but is obviously notappropriate 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 theDimension Array Bounds dialog which is invoked by holding down the Option key whenyou double-click in the value field of an array. If you prefer, you can force this dialog toalways be invoked by checking the Always show dialog when printing arrays box in thePreferences… dialog in the Edit menu (see the Preferences section).
The Dimension Array Bounds dialog allows you to specify the lower and upper bounds ofeach dimension in the array that you want to display as seen in the following figure:
Figure 10-7Dimension Array Bounds Dialog
The lower and upper bounds will default to the full dimension extent as it was establishedin the declaration statement for the variable in the source code. Dimensions beyond theoriginal 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 thedimension bounds data entry boxes.
Using the Fx Debugger 239
Fortran User Guide
The Format… button brings up the standard format dialog allowing you to specify adisplay format other than the default for the data type of the array. Two dimensionalarrays can be displayed in a special spread-sheet like window by clicking on the Matrixbutton in the 2D Array Display Format section:
Figure 10-8Matrix display
Note: Displaying more than one thousand array elements dynamically with theWatch All command may cause degradation in the performance of Fx orprogram failure due to insufficient memory.
All of the variables in a subroutine or function can be displayed at once using the Localscommand from the View menu. This command limits the display to those variables thathave function scope. Scope means the range within a program that a variable is visible orknown. 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 aredeclared in. For C language programs, scope can be global, local, or static, meaning theentire program, the current function, or the current file, respectively. The Globals andStatics 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 ofthe variable. Continuing the program or executing further statements will probably causethe 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 isavailable with the Watch commands in the Actions menu. The watch commands are issuedin same manner as the print commands. If the value of a dynamically updated variablechanges as the result of the execution of a program statement, the change will beindicated in the Symbols window by a change in color of the value field. The Watch Allcommand changes a Symbols window from static to dynamic, causing all variables in thewindow to be continuously updated.
240 Using the Fx Debugger
Fortran User Guide
Changing Variables
The value of any program variable may be easily modified or changed by entering thenew value (or portion thereof) as an expression in the value field for the variable and thenpressing the Return or Enter key. Only after the Return or Enter key is pressed is the newvalue accepted. If you change your mind, simply click the mouse button anywhere elseon 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 bechanged in a similar manner.
The standard text editing commands may be used in the value field to facilitate variablemodification.
Debugging Hints
Fx cannot debug your program for you, but it can provide you with the informationnecessary to track down programming errors and logic faults. The key to gaining thatinformation is asking the right questions. This section highlights some general guidelinesand tips for getting the most out of a debugging session.
• If a program gives different results each time it is run, look for uninitializedvariables and local variables that are being overwritten. Remember that localvariables must declared in a SAVE statement in Fortran and with a staticspecifier in the C programming language in order to retain their definition statusacross procedure references.
• You can display the values of the local variables in a previous referencingprocedure by changing the current frame in the Stack window as described in theControl section.
• If you find yourself in a procedure that you are not interested in, use the Returncommand in the Control menu to return immediately to referencing procedure.This command will execute all of the remaining statements in the function orsubroutine and return you to point where it was referenced.
• If the value returned by a function is completely wrong, yet single steppingthrough the function itself seems to calculate the result correctly, check thefunction declarations and definitions. Also, incorrectly typing the precision of afloating point function produces incorrect results due to the different internalrepresentations of single and double precision numbers.
• If you are experiencing difficulty with Macintosh toolbox functions, payparticular attention to the data types and method of passing parameter lists to theroutines. The VAL function must be to used when passing a parameter by value inFortran and a Universal Procedure Pointer must be used in any language to passthe address of call-back routine.
Using the Fx Debugger 241
Fortran User Guide
• Finding an obscure problem in a large program can be tedious and timeconsuming, especially if the program crashes. Try single stepping over calls tolarge subroutines and functions until the program fails. It is much easier toexamine a problem more closely once you have isolated the problem to anindividual procedure.
• Pointers are a powerful programming feature in any computer language, but theycan also cause a tremendous amount of havoc when they are not initializedcorrectly or when they unexpectedly lose their definition status. In both cases,using null or dangling pointer usually leads to disaster. Incorporating pointers inyour routines requires a defensive programming style.
FX MENUS AND WINDOWS
This section describes the menu selections that are used to perform Fx commands and thewindows that they control. The name of the command is given, followed by itsCommand-key equivalent (if any) and a description of its function.
File Menu
The File menu contains commands for creating new source andassembly language windows, opening application and symbolfiles, adding paths for source directories, closing individualwindows, and quitting Fx.
New Source ( N)
The New Source command is used to create additional source file and assembly languagewindows. These additional windows may be used to display various portions of theprogram in separate windows during a debugging session. New Assembly is shown in themenu when the front-most window is an assembly language display. The Code menuselection in the Windows menu (described below) can be used to select a file or aprocedure to be displayed in the current window.
Open… ( O)
This command is used to select an application for debugging. A standard file selectiondialog box is displayed to choose the symbol file for the application. The symbol file iscreated 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 codewindow 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.
242 Using the Fx Debugger
Fortran User Guide
Add Path…
The default search path for locating source files for the application being debugged is thefolder where the application and its symbol file were loaded. Since all of the source foran application may not reside in the same folder, the Add Path command is used to adddirectory paths to the search list for the other source files that were used to build theapplication.
Close ( W)
This command closes the front-most window. Holding the Option key down adds thefollowing functionality depending on the window type:
• If the front-most window is a Symbols window, the command becomes Close AllSymbols.
• If the front-most window contans a string variable, the command becomes CloseAll 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 theprogram 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 forFx.
Quit ( Q)
The Quit command exits Fx and returns you to the Finder. If necessary, Fx willautomatically 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 forcutting, copying, pasting, and clearing text. It is not possible to cut,paste, or clear text in an Fx source code or assembly languagewindow. However, text can be selected, copied, and pasted into textwindows opened by other applications. Text cannot be pasted into thetext-edit boxes of Fx dialogs.
Using the Fx Debugger 243
Fortran User Guide
Undo ( Z)
This command is not used by Fx, but is placed in the Edit menu for any desk accessorythat may use it.
Cut ( X)
This command can be used to remove selected text from the front-most window ofvarious applications and place it onto the Clipboard.
Copy ( C)
The Copy command duplicates selected text from the front-most window onto theClipboard. Text on the Clipboard may be pasted into editable windows opened by otherapplications.
Paste ( V)
This command can be used to paste copied text, such as variable or procedure names intoeditable windows opened by other applications.
Clear
Similar to Cut, this command removes the selected text from the front-most window butdoes not place a copy on the Clipboard. The Clipboard remains unchanged.
Select All ( A)
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 downmenu. The selections are: Environment, Format, and Startup.
Environment
244 Using the Fx Debugger
Fortran User Guide
Selecting Ignore file modification dates will suppress the warning messages issued when asource file has been modified since the program you are debugging was created.
Selecting Ignore unlocatable file errors will suppress the warning messages issued when asource file can not be found.
Selecting Prompt for symbol file at startup will cause Fx to automatically request a symbolfile when it is launched.
Selecting Fold all symbolic names to lower case will cause Fx to convert all variable namesto lower case before searching your programs symbol table.
The Always show dialog when printing arrays selection causes Fx to automatically invokethe array parameter display options dialog when an array name is double-clicked withoutthe requirement to hold down the Option key.
Format
Using the Fx Debugger 245
Fortran User Guide
Selecting Show types in Symbol windows by default will make displaying the types ofvariables and expressions in Symbol windows the default behavior.
Selecting Show C++ method names followed by class will reverse the order of C++ memberand class names in the Code window.
Use the Display function relative assembly addresses checkbox to show assembly languageaddresses as offsets from function names in addition to absolute addresses.
Selecting Show all available source files displays all files containing debugging informationin the file menu of source code windows and the Code window—not just those filescomprising 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 nothave recognizable tabsize information stored in their resource forks.
The Array Size text can is used to specify the number of array elements Fx will showwhen an entire array is displayed in a Symbol window.
Startup
This Preferences dialog allows you to control where the debugger stops after startup. Thisis particularly useful when debugging Windows applications where the entry point isWinMain, rather than the usual main. The debugger will search the list from top downuntil a valid entry point is found.
246 Using the Fx Debugger
Fortran User Guide
Control Menu
The Control menu is used to control the execution of theapplication being debugged with Continue, Stop, Return, StepInto, and Step Over commands. This menu also containscommands that can manipulate the stack frame for selectingwhich procedure is the current one for examining sourcecode and assembly language and the values of localvariables: Down, Home, Up, and Show Program Counter.
These are the most commonly used Fx commands and allbut Stop and Clear All Breakpoints have command keyequivalents.
Continue ( J)
Use this command to start or continue execution of the application. The application willexecute 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 ( K)
The Kill command stops the application and removes it from memory.
Stop
The Stop command stops execution of an application the next time it callsWaitNextEvent and displays the source code and/or assembly language associated withthe current location of the program counter in the source code window.
Note: If the application does not call WaitNextEvent again, the Stop commandwill have no effect.
Restart
The Restart command stops the application and re-executes it from the startup entry point.
Return ( R)
This command is used to automatically execute all of the remaining statements in thecurrent subroutine or function and return to the statement (source code and/or assemblylanguage) immediately following the point where it was referenced in the callingprocedure.
Using the Fx Debugger 247
Fortran User Guide
Step Into ( I)
The Step Into command is used to execute individual source code or assembly languagestatements. If a subroutine call or a function reference is encountered, the current codedisplay window changes to that procedure and execution stops there. If symbolinformation is not available for the procedure, an assembly language window will beopened for it (see the Assembly command in the Windows menu below). When source lineinformation is available, this command executes source statements by default and singleinstructions when the Option key is held down. If source information is not available, italways executes single instructions.
Step Over ( S)
Similar to the previous command, the Step Over command is also used to executeindividual source code or assembly language statements, but it treats subroutine calls andfunction references as though they were single statements. When source line informationis available, this command executes source statements by default and single instructionswhen the Option key is held down. If source information is not available, it alwaysexecutes single instructions.
Run To ( T)
The Run To command will execute the program until it gets to the line currently selectedin the source code or assembly language window or until a breakpoint is encountered
Down ( [)
The Down command changes the display in the source code and/or assembly languagewindow to that of the next referenced procedure. For example, if a procedure calledfunction1 is displayed in the source code window and it references a procedure calledfunction2, the Down command will display the source code for function2.
This command also changes the local symbol scope to that of the displayed procedureallowing you to examine the variables associated with the procedure.
If a stack trace window has been opened (see Stack in the Windows menu below), theDown command will highlight the next procedure down the window and display itsparameter list (its arguments).
Home ( H)
Use this command to return the source code and/or assembly language display to thebottom of the stack frame.
This command also changes the local symbol scope to that of the displayed procedure.
248 Using the Fx Debugger
Fortran User Guide
If a stack trace window has been opened (see Stack in the Windows menu below), theHome command will highlight the current procedure and display its parameter list (itsarguments).
Up ( ])
The Up command changes the display in the source code and/or assembly languagewindow to that of the previous referencing procedure. For example, if a procedure calledfunction2, which was referenced by a procedure called function1, is displayed in thesource code window and the Up command is given, the source code for function1 willbe displayed.
This command also changes the local symbol scope to that of the displayed procedureallowing 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 Upcommand 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 ( P)
Use the Show Program Counter command to return the source code display to the currentlocation in the application. The current location is the statement in the program whereexecution 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 thedisplay in source file and assembly language listings, open variabledisplay windows, change the value of a specified variable, change theformat used to display a variable, and go directly to the source code forspecified procedure.
The Globals, Locals, and Statics commands all display variables in thesame window — the Symbol window. The difference is in the scope ofthe variables displayed. Scope means the range within a program that avariable is visible or known. For Fortran programs, the only scopeavailable is local. Fortran variable names, even those in common blocks, are never visibleoutside of the subprogram that they are declared in. For C language programs, all threescopes are available as described below.
Using the Fx Debugger 249
Fortran User Guide
Address…
To go directly to a specific address in an assembly language listing without scrolling, usethe Address… command.
Line…
To go directly to a specific line in a source file listing without scrolling, use the Line…command.
Next ( 9)
Displays the next screen full of assembly language instructions for the function visible inthe Assembly window.
Prev ( 0)
Displays the previous screen full of assembly language instructions for the functionvisible in the Assembly window.
Globals
The Globals command displays a list of all of the variables with application scope in theSymbols window. The Symbols window is first opened if one does not exist. For Fortrandebugging, 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 theSymbols window. The Symbols window is first opened if one does not exist. For Fortrandebugging, all variables are considered local — even variables in common blocks sincetheir names have only local scope. For C debugging, local variables are those with onlyfunction scope.
250 Using the Fx Debugger
Fortran User Guide
Statics
The Statics command displays a list of all of the variables with file scope in the Symbolswindow. The Symbols window is first opened if one does not exist. For Fortrandebugging, 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 newvalue 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 directlyin the Symbols window by entering the new value in the value field andpressing Return or Enter.
View As…
Use this command to control the format of the value display of the variable whose nameis highlighted in the Symbol window.
Code For “”
To go directly to the source code and/or assembly language for a procedure nameselected in any text edit pane without scrolling or using the Code command in Windowsmenu, use the Code For “” command.
Using the Fx Debugger 251
Fortran User Guide
Actions Menu
The Actions menu is used for finding strings in a source codewindow, printing the values of variables and addressexpressions, and setting breakpoints on selected procedurenames. The Print commands display the current value of thespecified variable or address expression each time thecommand is given, maintaining a history of the values. TheWatch commands update the value display each time theprogram stops, either by single stepping or by reaching abreakpoint. Values can be displayed by selecting strings in thesource code window or by directly typing address expressionsinto dialog boxes.
Find… ( F)
The Find… command opens a dialog for entering a string that is then searched for incurrent source code window. The Find… command is case sensitive.
Find Again ( G)
Use this command to find the next occurrence of the string specified with the Find…command.
Print “” ( E)
The Print “” command displays the value of the variable or address expression currentlyselected in the source code window. The value is displayed in a format appropriate for itsdata type. To display the value in other formats, use the Print As… command describedbelow or the View As… command in the View menu, described earlier.
Print * “” ( D)
If the symbol or address expression that is selected in the source code window is apointer variable, choose the Print * “” command which will first dereference the variablebefore displaying it. The value is displayed in a format appropriate for its data type. Todisplay the value in other formats, use the Print As… command described below.
252 Using the Fx Debugger
Fortran User Guide
Print As…
The Print As… command is used to display the value of any variable in the currentprocedure in any format required. The command displays a dialog box where the formatof the output is selected and the name of variable is entered.
Watch “”
The Watch “” command displays and continuously updates the value of the variable oraddress expression currently selected in the source code window. The display is updatedeach time the program stops, either at a breakpoint or after a single step. The value isdisplayed 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 apointer variable, choose the Watch * “” command which will first dereference the variablebefore displaying it. Thereafter, it will be continuously updated each time the programstops, either at a breakpoint or after a single step. The value is displayed in a formatappropriate 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 thevariables in the Symbols window. This command is dimmed if the Symbols window is notthe front-most window.
Using the Fx Debugger 253
Fortran User Guide
Watch As…
The Watch As… command is used to continuously display the value of any variable in thecurrent procedure in any format required. The command displays a dialog box where theformat of the output is selected and the name of variable is entered. Thereafter, the valueis 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 framedynamically.
Set Breakpoint On “”
The Set Breakpoint On “” command establishes a breakpoint at the entry point of theprocedure that is currently selected in the source code window.
Profile Menu
This menu is used to configure the various profiling parameters asdescribed in the section Profiling With Fx and to enable or disableprofiling. The best profiling results are obtained when the program iscompiled with the -p option.
Configure…
This command is used to configure the profiler. Refer to the section Profiling With Fxfor details on this command.
On
This toggle command turns profiling on (or off). Refer to the section Profiling With Fxfor details on this command.
254 Using the Fx Debugger
Fortran User Guide
profmt…
This command launches the program used to display profile statistics. Refer to thesection Using Profmt for details on this command.
Windows Menu
This menu is used to open windows for displayingadditional information such as assembly languagelistings, memory dumps in various formats, thePowerPC 601 register values, and stack frame traces.There are also menu selections available for selectingsource code and class browsers. If the particularwindow is already open, the command will bring it tothe front. As Source, Assembly, and Symbol windowsare opened, their names will be appended to the bottomof 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 palettecontaining 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 aoverlapped or cascaded manner.
Assembly ( 1)
Use the Assembly command to display an assembly language listing of the applicationbeing debugged. A window will be opened at the location in memory of the currentprogram counter. The text marked by bars on the left side of the listing represents themachine code for the current high level language statement. The Address… menuselection in the View menu can be used to go directly to a memory address in theassembly listing.
All of the Control menu commands, such as Continue, Step Into, and Step Over, areavailable in an assembly language window, but it is not possible to single step throughApple ROM code.
Using the Fx Debugger 255
Fortran User Guide
Breakpoints ( 2)
The Breakpoints command opens a window listing all of the breakpoints that have beenset in the application.
Each line lists the file and line number where the breakpoint is set, whether it is currentlyenabled or disabled, the current count and the skip count (in parentheses), and thecondition. The skip count determines the number of times this statement must executebefore stopping and the current count is the number of times the statement has beenexecuted already without stopping. The condition is a logical expression stated in thesource language of the file. The condition, if present, must be met in order for thebreakpoint 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 onthe second line and set the condition to:
C .GT. 100.0
256 Using the Fx Debugger
Fortran User Guide
Selecting an individual breakpoint in this window by double-clicking on it opens thebreakpoint control dialog:
This dialog can be used to set or modify the location — expressed as either a file nameand line number for source code, or as an address for assembly language. The conditionand the skip count may also be set or modified, as well as whether the breakpoint isenabled or disabled
Classes ( 3)
The Classes command opens a window displaying the names of all the classes visible inthe current scope, along with a list of their member functions and a graphicalrepresentation of their inheritance hierarchy. Selecting a class name in the left pane willdisplay its member functions in the right pane. Double clicking on the name of a memberfunction will display it’s source code. A breakpoint can be set on the member function byselecting its name and using the Set Breakpoint On command in the Action menu. Clickingon a class name in the inheritance pane selects it in the class list and shows its memberfunctions.
Using the Fx Debugger 257
Fortran User Guide
Code ( 4)
Use this command to open a file browser window. The code window is divided into twopanes:
The left pane is a list of the files that comprise the application. Selecting one of these filenames 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 inthe front-most window. (Use the New Source command in the File menu to create a newsource code window.)
You may need to use the Add Path… command in the File menu if the source file is notlocated in the same folder as the application.
Memory ( 5)
This command is used to directly examine memory by specifying an address rather thanthe symbolic name of a variable. The Memory command displays the following dialog:
Location specifies the memory address to examine (hexadecimal numbers should beentered as 0xnnn). The format and size are controlled with radio buttons as shown.
258 Using the Fx Debugger
Fortran User Guide
Registers can be specified as addresses by entering them as they appear in the Registerwindow (see below). Clicking on the OK button produces a window similar to the oneshown below:
General Registers ( 6)
The General Registers command opens a window which displays the contents of thePowerPC registers, as well as the program counter and the condition code bits. Thiswindow is updated after every single step command and whenever breakpoints areencountered. The value of a register can be changed by selecting the register, printing itin a Symbols window, and entering a new value in the value field.
Using the Fx Debugger 259
Fortran User Guide
FPU Registers
The FPU Registers command opens a window which displays the contents of thePowerPC floating point registers. This window is updated after every single stepcommand and whenever breakpoints are encountered. The value of a register can bechanged by selecting the register, printing it in a Symbols window, and entering a newvalue in the value field.
Stack ( 7)
The Stack command opens a window which displays a trace of the stack frame. Thecurrent procedure is highlighted:
The window displays a list of the procedures in the current call chain, starting with thefirst 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 thefile is also displayed.
Symbols ( 8)
This command brings the Symbols window to the front.
260 Using the Fx Debugger
Fortran User Guide
PROFILING
This section describes how to prepare a program for profiling, how to use Fx to gatherexecution statistics, and then how to use Profmt, a separate program, to analyze theinformation that is collected.
Options For Profiling
The following two sections discuss the options that are given to the compiler and thelinker when you are preparing a program for profiling.
Compiler Options
The -p option (the Profiler Information checkbox in the Compiler Control… commandodialog) is used with either Absoft Fortran 77 or Absoft C/C++ to direct the compiler toadd code to the compiled program which counts the number of times a particularprocedure (subprogram or function) is called.
Figure 10-9Fortran compiler option
This option can be used in conjunction with any other option or set of options, includingoptimization. The -g compiler option is not necessary and probably should not be usedsince it prevents the compiler from performing certain optimizations that may beimportant to the execution speed of the program.
Note: A program compiled without the -p option can still be profiled, but youwill learn only the amount of time spent in an individual procedure, notthe number of times it was called, and therefore, not how long it takes toexecute per call.
Using the Fx Debugger 261
Fortran User Guide
Linker Options
The -sym on option (the Symbolic Output checkbox in the Debug Information… commandodialog) must be added to the command line for the Absoft linker, lnk, to produce asymbol file containing information on the entry points of the program. If you are usingthe commando dialog for the compiler, this will be done automatically when you selectthe -p option as described above. If you have created a Build script, you should add theoption to the command line for lnk.
Figure 10-10Linker option
The symbol file created by the linker with have the same name as the application with thecharacters .FxSYM appended to the end.
Note: It is not necessary to compile the program with the -g compiler option forthe linker to produce a symbol file containing program entry points. The-g option is only required when symbolic information on programvariables is needed which is not the case when profiling.
Profiling With Fx
262 Using the Fx Debugger
Fortran User Guide
To profile a program, begin by launching Fx in the normal manner as described in thesection Starting A Debugging Session earlier in this chapter. After the program and thesymbol table have been loaded, select the Configure… command from the Profile menu:
Figure 10-11Profile Configuration Dialog
The Save Profile Information As: text box is used to specify the name of the file in thecurrent directory to which the profile statistics will be written. If you want the profilestatistics to be written to a different directory, click on the Save As… button to bring up astandard file selection dialog box. The default is to write the statistics to a file namedProfiler.Out in the current directory.
Use the Sample Rate: pop-up menu to indicate the granularity of profiling which is howoften you want the profiler to examine the program counter. A smaller number means itwill check more often, giving more accurate statistics, but increase the overall amount oftime required to profile your program.
After you are satisfied with the configuration settings, click on the OK button andprofiling will automatically be turned on. Begin profiling by selecting Continue from theControl menu and the various execution statistics will be gathered automatically as theprogram 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 inthe Profile menu can be used to control when statistics are accumulated. First, use thecommand to turn off profiling after you have set the configuration parameters, then set abreakpoint at the point you wish to begin profiling and execute to that point. When thebreakpoint 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 canbe invoked directly from Fx by selecting profmt… from the Profile menu, or it can belaunched from the desktop. Profmt contains four menus — the normal Apple menu aswell as File, Edit, and Sort menus.
Using the Fx Debugger 263
Fortran User Guide
The display is tabular in layout and consists of the name of each procedure followed bythe number of calls to the procedure, the total amount of time, in tenths of seconds, spentin 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 thecommands in the Sort menu. The -p compiler option is necessary for the calls or time/callinformation to be valid.
If the procedure name is displayed in boldface, the procedure has line number statisticsassociated with it. Click on the procedure name to open a new window displaying lineoriented profile information about the procedure.
If the procedure name is displayed in plain text, holding the mouse button down whilepointing 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 Profmtcommands.
File Menu
The File menu contains commands for opening and closing profile outputfiles, displaying general information about the program, page setup andprinting the output window, and quitting Profmt.
Open… ( O)
This command is used to select a profile output file for display. A standard file selectiondialog box is displayed to choose the profile output file for the application. The profileoutput file is created by Fx and will have the default name of Profiler.Out, althoughyou may give it any other name you choose. Only one profile output file may bedisplayed at a time.
Close ( W)
Use this command to close a profile output file so that another may be opened.
Info ( I)
Use this command to display general information and statistics about the profiledprogram.
Page Setup…
Use this command to make custom page choices for printing.
Print… ( P)
Use this command to print a profile display.
264 Using the Fx Debugger
Fortran User Guide
Quit ( Q)
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, orclear text in Profmt. However, the menu selections are available fordesk accessories that may need them. This menu also containscommands for editing the appearance of the profile display. All of thedata elements displayed may be hidden or shown with the commandsin this menu. The settings made from this menu are saved when aprofile output file is closed and reestablished when it is reopened.
Undo ( Z)
This command is not used by Profmt, but is placed in the Edit menu for any deskaccessory that may use it.
Cut ( X)
This command is not used by Profmt, but is placed in the Edit menu for any deskaccessory that may use it.
Copy ( C)
This command is not used by Profmt, but is placed in the Edit menu for any deskaccessory that may use it.
Paste ( V)
This command is not used by Profmt, but is placed in the Edit menu for any deskaccessory that may use it.
Clear
This command is not used by Profmt, but is placed in the Edit menu for any deskaccessory that may use it.
Hide Time
Use this command to hide (or show if already hidden) the column of values representingthe total number of tenths of seconds spent in each procedure.
Using the Fx Debugger 265
Fortran User Guide
Hide Calls
Use this command to hide (or show if already hidden) the column of values representingthe total number of calls to each procedure.
Hide Time/Call
Use this command to hide (or show if already hidden) the column of values representingthe 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 visualanalysis of the results of the profiling session. A list sorted by timealone may suggest that a particular procedure is inefficient, but whensorted by time/call, you find that although it is called thousands oftimes, it executes extremely quickly.
By Name
Use this command to sort the list of procedures in name order. The Ascending orDescending 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 histogramrepresents 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. Thisinformation 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 ineach procedure per call. This information is only valid for those procedures compiledwith the -p compiler option. The histogram represents the relative amount of time takento execute each procedure per call.
266 Using the Fx Debugger
Fortran User Guide
Ascending
Use this command to set the sort order (By Name, By Time, By Calls, or By Time/Call) toascending or increasing order.
Descending
Similar to the previous command, the Descending command is also used to change thesort order, but to descending or decreasing order.
267
Fortran User Guide
Appendix A
Absoft Compiler Option Guide
This appendix summaries the options for the Absoft Fortran 90/95, FORTRAN 77, andC/C++ compilers. Refer to the chapter, Using the Compiler for detailed descriptions ofthe options
ABSOFT COMPILER OPTIONS
Option Effect
-c suppresses creation of an executable file — leaves compiled files inobject 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 runfaster without the expense of application size or memory usage
-o name directs the compiler to produce an executable file called name wherename is a Windows file name
FORTRAN 90/95 GENERAL OPTIONS
-en causes the compiler to issue a warning whenever the source codecontains 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 thecompilation process
-v directs the compiler to print status information as the compilationprocess proceeds
268 Absoft Compiler Option Guide
Fortran User Guide
-N80 causes the compiler to generate code to write the name of the currentlyexecuting 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 firsterror that it encounters.
-V causes the f90 compiler to display its version number.
-eR directs the compiler to place information in the debugger symbol tablesfor 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 andconstants specified with the D exponent to be converted to the defaultreal kind.
-ej causes all DO loops to be executed at least once, regardless of the initialvalue 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 inFixed-Form source format.
Absoft Compiler Option Guide 269
Fortran User Guide
-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 valueis 0 or false.
-TMS7D recognize Microsoft style compiler directives beginning with a ‘$’ incolumn 1.
FORTRAN 90/95 OTHER OPTIONS
-YPEI Pointers are Equivalent to Integers allows a Cray-style pointer to bemanipulated 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 codecontains an extension to the ANSI FORTRAN 77 standard
!Q19 used when more than one symbolic name is used to reference avariable’s memory location. This can occur when pointers are used,when variables in COMMON are passed as arguments, or when twodummy arguments are the same actual argument.
-q suppresses any messages printed to standard output during thecompilation process
-v directs the compiler to print status information as the compilationprocess proceeds
-N124 causes the compiler to generate code to write the name of the currentlyexecuting 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 runtime error messages
-x replaces any occurrence of X or D in column one with a blank character:allows a restricted form of conditional compilation
270 Absoft Compiler Option Guide
Fortran User 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 of1024 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 isassigned 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 valueset with RECL to be interpreted as the number of 32 bit words in arecord 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 initialvalue of the iteration count (FORTRAN 66 convention)
-i changes the default storage length of INTEGER and LOGICAL datatypes to 2 bytes
-N102 directs the compiler to zero extend INTEGER*1 variables to unsignedentities with a range of 0-255 when loaded from memory
-N15 causes the compiler to define SUBROUTINE and FUNCTION nameswith a trailing underscore
FORTRAN 77 MISCELLANEOUS OPTIONS
Absoft Compiler Option Guide 271
Fortran User Guide
-N2 uses only double precision or double complex transcendental intrinsics
-N7 extends the sign of a value returned from BYTE, and WORD intrinsicfunctions
-N1 causes all variables initialized with DATA statements to be stored asstatic variables.
-N20 directs the compiler to always evaluate operators of equal precedencefrom left to right (except for exponential operators)
-N113 changes REAL and COMPLEX data types without explicit lengthdeclara-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 spacebetween them
-N34 automatically align COMMON block variables
FORTRAN 77 FORMAT OPTIONS
-8 directs the compiler to accept source code written in Fortran 90/95 FreeSource 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 column72 up to column 132
-N26 force the compiler to consider the byte ordering of all unformatted filesto be big-endian by default
-N27 force the compiler to consider the byte ordering of all unformatted filesto be little-endian by default
272 Absoft Compiler Option Guide
Fortran User Guide
FORTRAN 77 OTHER OPTIONS
-g generates symbol information for Fx™.
-N111 directs the compiler to place information in the debugger symbol tablesfor all structures whether or not they have associated storage
-N114 issue a warning diagnostic, rather than an error, for undeclared variablesin 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 currentlyexecuting procedure to standard out.
-ptv causes the compiler to print a message to stderr whenever a template isinstantiated.
-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 thecompiler aborts.
Absoft Compiler Option Guide 273
Fortran User Guide
-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 filewhich 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++ ReferenceManual .
-std allows you to use the namespaces and runtime type information featuresANSI C++ in your source code.
-A indicates source which conforms to the ANSI X3.159-1989 standard forthe C programming language.
-K used with older style Kernighan and Ritchie C.
275
Fortran User Guide
Appendix B
Linker Error Messages
This appendix lists possible linker and MPW errors that may be encountered whencompiling 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 isoften preceded by a “frozen” machine. For Vaccine, a Control Panel option canpermit MPW links. See the documentation for the virus detector for permittinglinking.
### 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 usedor 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 Systemfolder and/or reduce the size of the RAM cache in the Control Panel.
• Use the fsplit utility to break large programs into smaller, moremanageable, files. See Chapter 8 for details about fsplit.
• Use the “Use files for temporary storage” option (-F) which causes thecompiler to use disk space to store temporary information rather thanusing memory. This will slow compilation speed and use more diskspace, but more memory will be available during compilation.
• Increase the SIZE resource of MPW if you are using MultiFinder. Seethe 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 memoryused by Absoft Fortran 90/95 during compilation.
276 Linker Error Messages
Fortran User Guide
• If using System 6, use the Finder instead of MultiFinder. SinceMultiFinder allocates memory to other applications and the systemitself, 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 anapplication that is already executing. To prevent this, quit the application andrecompile.
# 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.
277
Fortran User Guide
Appendix C
ASCII Table
ASCII codes 0 through 31 are control codes that may or may not have meaning on theMacintosh. They are listed for historical reasons and may aid when porting code fromother systems. Codes 128 through 255 are extensions to the 7-bit ASCII standard and thesymbol displayed depends on the font being used; the symbols shown below are from theTimes New Roman font. Most of these characters may be typed with keystrokes; use theKey Caps desk accessory to determine which keystrokes to use. The Dec, Oct, and Hexcolumns refer to the decimal, octal, and hexadecimal numerical representations.
Character Dec Oct Hex DescriptionNULL 0 000 00 nullSOH 1 001 01 start of headingSTX 2 002 02 start of textETX 3 003 03 end of textECT 4 004 04 end of transENQ 5 005 05 enquiryACK 6 006 06 acknowledgeBEL 7 007 07 bell codeBS 8 010 08 back spaceHT 9 011 09 horizontal tabLF 10 012 0A line feedVT 11 013 0B vertical tabFF 12 014 0C form feedCR 13 015 0D carriage returnSO 14 016 0E shift outSI 15 017 0F shift inDLE 16 020 10 data link escapeDC1 17 021 11 device control 1DC2 18 022 12 device control 2DC3 19 023 13 device control 3DC4 20 024 14 device control 4NAK 21 025 15 negative ackSYN 22 026 16 synch idleETB 23 027 17 end of trans blkCAN 24 030 18 cancelEM 25 031 19 end of mediumSS 26 032 1A special sequenceESC 27 033 1B escapeFS 28 034 1C file separatorGS 29 035 1D group separatorRS 30 036 1E record separatorUS 31 037 1F unit separator
Character Dec Oct Hex Description 32 040 20 space! 33 041 21 exclamation" 34 042 22 quotation mark# 35 043 23 number sign$ 36 044 24 dollar sign% 37 045 25 percent sign& 38 046 26 ampersand' 39 047 27 apostrophe( 40 050 28 opening paren) 41 051 29 closing paren* 42 052 2A asterisk+ 43 053 2B plus, 44 054 2C comma- 45 055 2D minus. 46 056 2E period/ 47 057 2F slash0 48 060 30 zero1 49 061 31 one2 50 062 32 two3 51 063 33 three4 52 064 34 four5 53 065 35 five6 54 066 36 six7 55 067 37 seven8 56 070 38 eight9 57 071 39 nine: 58 072 3A colon; 59 073 3B semicolon< 60 074 3C less than= 61 075 3D equal> 62 076 3E greater than? 63 077 3F question mark
278 ASCII Table
Fortran User Guide
Character Dec Oct Hex Description@ 64 100 40 commercial atA 65 101 41 upper case letterB 66 102 42 upper case letterC 67 103 43 upper case letterD 68 104 44 upper case letterE 69 105 45 upper case letterF 70 106 46 upper case letterG 71 107 47 upper case letterH 72 110 48 upper case letterI 73 111 49 upper case letterJ 74 112 4A upper case letterK 75 113 4B upper case letterL 76 114 4C upper case letterM 77 115 4D upper case letterN 78 116 4E upper case letterO 79 117 4F upper case letterP 80 120 50 upper case letterQ 81 121 51 upper case letterR 82 122 52 upper case letterS 83 123 53 upper case letterT 84 124 54 upper case letterU 85 125 55 upper case letterV 86 126 56 upper case letterW 87 127 57 upper case letterX 88 130 58 upper case letterY 89 131 59 upper case letterZ 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 accenta 97 141 61 lower case letterb 98 142 62 lower case letterc 99 143 63 lower case letterd 100 144 64 lower case lettere 101 145 65 lower case letterf 102 146 66 lower case letterg 103 147 67 lower case letterh 104 140 68 lower case letteri 105 151 69 lower case letterj 106 152 6A lower case letterk 107 153 6B lower case letterl 108 154 6C lower case letterm 109 155 6D lower case lettern 110 156 6E lower case lettero 111 157 6F lower case letterp 112 160 70 lower case letterq 113 161 71 lower case letterr 114 162 72 lower case letters 115 163 73 lower case lettert 116 164 74 lower case letteru 117 165 75 lower case letterv 118 166 76 lower case letterw 119 167 77 lower case letterx 120 170 78 lower case lettery 121 171 79 lower case letterz 122 172 7A lower case letter{ 123 173 7B opening brace| 124 174 7C vertical bar} 125 175 7D closing brace
~ 126 176 7E tilde127 177 7F delete
ASCII Table 279
Fortran User Guide
Character Dec Oct Hex� 128 200 80� 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
¾ 190 276 BE¿ 191 277 BF
280 ASCII Table
Fortran User Guide
Character Dec Oct HexÀ 192 300 C0Á 193 301 C1Â 194 302 C2Ã 195 303 C3Ä 196 304 C4Å 197 305 C5Æ 198 306 C6Ç 199 307 C7È 200 310 C8É 201 311 C9Ê 202 312 CAË 203 313 CBÌ 204 314 CCÍ 205 315 CDÎ 206 316 CEÏ 207 317 CFÐ 208 320 D0Ñ 209 321 D1Ò 210 322 D2Ó 211 323 D3Ô 212 324 D4Õ 213 325 D5Ö 214 326 D6× 215 327 D7Ø 216 330 D8Ù 217 331 D9Ú 218 332 DAÛ 219 333 DBÜ 220 334 DCÝ 221 335 DDÞ 222 336 DEß 223 337 DF
Character Dec Oct Hexà 224 340 E0á 225 341 E1â 226 342 E2ã 227 343 E3ä 228 344 E4å 229 345 E5æ 230 346 E6ç 231 347 E7è 232 350 E8é 233 351 E9ê 234 352 EAë 235 353 EBì 236 354 ECí 237 355 EDî 238 356 EEï 239 357 EFð 240 360 F0ñ 241 361 F1ò 242 362 F2ó 243 363 F3ô 244 364 F4õ 245 365 F5ö 246 366 F6÷ 247 367 F7ø 248 370 F8ù 249 371 F9ú 250 372 FAû 251 373 FBü 252 374 FCý 253 375 FDþ 254 376 FEÿ 255 377 FF
281
Fortran User Guide
Appendix D
Bibliography
FORTRAN 90/95
These books and manuals are useful references for the Fortran 90/95 programminglanguage and the floating point math format used by Absoft Pro Fortran on theMacintosh.
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 toFortran90, Unicomp, Inc (1994)
Jeanne C. Adams, Walter S. Brainerd, Jeanne T. Martin, and Brian T. Smith, Fortran Top90, 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 ofIEEE 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 thefloating 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 PublishingCompany (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)
282 Bibliography
Fortran User Guide
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 ofIEEE Task P754, 10662 Los Vaqueros Circle, Los Alamitos, CA 90720 (1981)
M. Abramowitz and I.E. Stegun, Handbook of Mathematical Functions, U.S. Departmentof Commerce, National Bureau of Standards (1972)
C AND C++
These books and manuals are useful references for the C and C++ programminglanguages and the floating point math format used by Absoft Pro Fortran on theMacintosh.
Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, PrenticeHall (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 PublishingCompany (1976)
Brian W. Kernighan and P.J. Plauger, The Elements of Programming Style, McGraw-HillBook Company (1978)
Bibliography 283
Fortran User Guide
American National Standard Programming Language C, X3.159-1989, ANSI, 1430Broadway, New York, N.Y. 10018
COMPUTER, A Proposed Standard for Binary Floating-Point Arithmetic, Draft 8.0 ofIEEE 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 website in the “developer” area:
http://www.apple.com
Apple Computer Inc., Inside Macintosh, volumes I-VI, Addison-Wesley PublishingCompany (1985-1991)
Apple Computer Inc., Programmer’s Introduction to the Macintosh, Addison-WesleyPublishing Company (1989)
Apple Computer Inc., Inside Macintosh: RISC System Software, Addison-WesleyPublishing Company (1994).
Apple Computer Inc., Inside Macintosh: RISC Numerics, Addison-Wesley PublishingCompany (1994).
Apple Computer Inc., Human Interface Guidelines, Addison-Wesley PublishingCompany (1987).
Apple Computer Inc., Macintosh Programmer’s Workshop, Apple Programmers andDevelopers Association (1985-1991
Apple Computer Inc., Macintosh Technical Notes, Apple Programmers and DevelopersAssociation (1985-1991).
285
Fortran User Guide
Appendix E
Technical Support
The Absoft Technical Support Group will provide technical assistance to all registeredusers of current products. They will not answer general questions about operatingsystems, operating system interfaces, graphical user interfaces, or teach programming.For further help on these subjects, please consult this manual and any of the books andmanuals listed in the bibliography.
Before contacting Technical Support, please study this manual and the languagereference manuals to be sure your problem is not covered here. Specifically, refer to thechapter Using The Compilers in this manual. To help Technical Support provide a quickand accurate solution to your problem, please include the following information in anycorrespondence or have it available when calling.
Product Information:
Name of productVersion numberSerial numberVersion 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.
286 Technical Support
Fortran User Guide
Contacting Technical Support:
Address: Absoft CorporationAttn: Technical Support2781 Bond StreetRochester Hills, MI 48309
telephone: (248) 853-0095 9am - 3pm ESTFAX (248) 853-0108 24 Hoursemail [email protected] 24 HoursWorld Wide Web http://www.absoft.com
287
Fortran User Guide
Appendix F
Differences Between Pro Fortran V6.2 and V7.0
This appendix summarizes changes form Absoft Pro Fortran V6.2 to V7.0. Whereapplicable, sections of the manuals are listed for reference.
CARBON LIBRARY
All compilers now support code production compatible with the Macintosh CarbonLibrary. The Carbon Library allows you to produce programs that are compatible withboth the classic Macintosh environment and the native Macintosh OS X environment.See the chapters Using the Compilers and The Macintosh Runtime WindowEnvironment for details.
SHARED LIBRARIES
The creation of shared libraries is not supported for MRWE applications or any librarythat uses Fortran I/O.
FORTRAN 90
Promote to Double Precision. The Fortran 90 compiler now supports automaticpromotion 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 of32-bit INTEGER(KIND=4) to equivalent 64-bit data types (KIND=8). See the chapterUsing the Compilers for details.
Debugging Options. The Fortran 90 compiler now supports a number of options forchecking that array indices are with the bounds of an array, that character substringexpressions do not specify a range outside of the variable, array conformance, andPOINTER 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 automaticpromotion of 32-bit INTEGER*4 to equivalent 64-bit data types INTEGER*8. See thechapter Using the Compilers for details.
288 Differences Between Pro Fortran V6.2 and V7.0
Fortran User Guide
289
Fortran User Guide
Appendix G
Interfacing with MetroWerks CodeWarrior
This appendix describes how to interface object modules produced by the Absoft ProFortran compilers for PowerPC with MetroWerks projects. The Absoft compilersproduce code that may be used in MetroWerks Codewarrior projects. However, becausethe Codewarrior environment does not produce object files that are compatible with theAbsoft linker, the final program must be created inside Codewarrior. This appendixprovides details on importing Pro Fortran object files into a Codewarrior project. Forinformation on inter-language calling conventions, refer to the chapter MacintoshProgramming.
PRODUCING THE FORTRAN OBJECT CODE
Before you can import Pro Fortran code into a Codewarrior project, you must firstcompile it into object format. This step is performed inside the MPW environment usingthe Absoft Pro Fortran compiler. If you have only a single routine, you can simply selectthe No executable (object file only) option in addition to any other options your code mayrequire. However, if you are using many routines or if your FORTRAN code makes useof COMMON blocks, you will need to create a static library using the Absoft linker. Forinformation on creating libraries, refer to the chapter Building Programs, earlier in thismanual.
ADDING FORTRAN OBJECT FILES TO A CODEWARRIOR PROJECTS
After starting Codewarrior and opening your project, use the Add… item, located in theProject menu, to add your routine or library to your project. If your FORTRAN codemakes use of INTRINSIC functions or I/O statements, you will also need to add theFORTRAN library, libfmath.o and libfio.o, to your project as well. Finally, rebuildyour 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 debuggingAbsoft Pro Fortran code with the MetroWerks debugger. You can view source code, setbreakpoints, and examine the values of simple variables. You cannot examine multi-dimensional arrays, variables within COMMON blocks, or variables declared with theRECORD or POINTER statement.
291
Fortran User Guide
Appendix H
Language Systems Fortran Extensions
This appendix describes the implementation of Language Systems Fortran extensionssupported by the Absoft FORTRAN 77 Compiler.
STRING
STRING is a type statement and is used to declare a string entity compatible with Pascalstrings. The first data byte of a STRING is set to the logical length of the string, limitingthe length of a character entity declared in this manner to 255 bytes. With the exceptionof internal files and substring expressions, a STRING can be used anywhere aCHARACTER argument can be used.
POINTER
This is a declaration statement for declaring variables that will contain the address ofother 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 tomanipulate the address it contains. It is dereferenced (the value of what it points to isextracted) by appending the operator, ^, to the name.
LEAVE
This statement has the same meaning as the EXIT statement (See Control Statements inthe FORTRAN 77 Reference Manual) and provides a convenient means for abnormaltermination of a DO loop. The LEAVE and EXIT statements cause control of execution to betransferred 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 DATAStatements in the FORTRAN 77 Reference Manual). The variables specified with aGLOBAL statement are made externally visible. It can be used in conjunction with GLOBALDEFINE to create global variables for the whole file.
292 Language Systems Fortran Extensions
Fortran User Guide
CGLOBAL
The syntax of this statement is similar to the SAVE statement (see Specification and DATAStatements in the FORTRAN 77 Reference Manual). The variables specified with aCGLOBAL statement are not affected by case folding and are made externally visible. It canbe 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 DATAStatements in the FORTRAN 77 Reference Manual). The variables specified with aPGLOBAL statement are folded to upper case and made externally visible. It can be used inconjunction 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 andDATA Statements in the FORTRAN 77 Reference Manual). The functions specified with aCEXTERNAL statement pass all of their arguments by value as the default. An argumentcan 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 andDATA Statements in the FORTRAN 77 Reference Manual). The functions specified with aPEXTERNAL statement pass all of their arguments by value as the default. An argumentcan be passed by reference if the %REF intrinsic function is used. Note that this statementhas 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 argumentsto 1-, 2-, and 4-byte integers respectively.
JSIZEOF
This function returns an integer that represents the size of its argument in bytes. It isidentical to the SIZEOF function (see Programs, Subroutines, and Functions in theFORTRAN 77 Reference Manual).
%VAL, %REF, AND %DESCR
When appearing in the formal argument list of a FUNCTION or SUBROUTINE declarationstatement, these statements use the syntax of a function reference, but have the affect ofdeclaring the passing method of the argument. %DESCR has no effect (but will generate a
Language Systems Fortran Extensions 293
Fortran User Guide
warning diagnostic), %REF is the default, and %VAL is the same as using the VALUEdeclaration statement (see Specification and DATA Statements in the FORTRAN 77Reference Manual). The % is not optional in this usage.
LANGUAGE SYSTEMS INCLUDE FILES
There are some syntactical difficulties in several of the Language Systems API includefiles that are ignored by the Language Systems Fortran compiler. These are detected bythe Absoft FORTRAN 77 compiler which will issue a diagnostic when they areencountered.
Index
Fortran User Guide
≈ character ................................................................41? character.................................................................41≥ symbol ...................................................................40132 column source code....................................87, 107386, porting from ....................................................12772 Column Window command ...............................133A/UX environment..................................................128Absoft address.........................................................286Absoft compilers.....................................................289Absoft Fortran 77 compiler
previous version.................................................289access path error......................................................276Actions menu ..........................................................251Add Path command.........................................233, 242Adding Menus.........................................................167Address command...................................................249aggregate.................................................................237Alert command .........................................................64Alert dialog box ......................................................183Alias command .........................................................61Align menu command...............................................25alignment
automatically align COMMON .........................109Alphabetical menu command....................................30appcbe tool..............................................................136Apple events ...........................................................201Apple Events...........................................................172
class ...................................................................173ID 173target..................................................................173
Apple menu...............................................................23application icon...............................................153, 222arguments, tool.............................................206array
boundary checking.........................................93, 98arrays ......................................................................237Ascending command...............................................266ASCII table .............................................................277Assembly command................................................254assembly language ..........................................241, 247
interfacing with FORTRAN ..............................220balloon help ....................................................155, 223basic optimizations ...........................................86, 102Beep command .........................................................65BLOCK=-1 specifier...............................................105BNDL resource ...............................................154, 223branch instructions ..............................................83, 98breakpoint condition .......................................236, 255breakpoint control dialog ................................235, 256breakpoints..............................................................234Breakpoints command ............................................255Browse menu command............................................29By Calls command..................................................265By Name command.................................................265By Time command..................................................265By Time/Call command..........................................265BYTE sign extension ..............................................109C
function results ..................................................210interfacing with FORTRAN(see interfacing
FORTRAN and C)
Carbon........................................................................ 4carriage control, printing .................. 206carriage returns
adding ............................................................... 125changing from line feeds................................... 126
Cascade command.................................................. 254CASE DEFAULT .................................................. 109Catenate command ................................................... 52Change command................................................... 250changing linefeed character.................................... 126Character Map application ..................................... 277check array boundaries............................................. 98CheckHEXA tool ................................................... 131Choose command ..................................................... 51Chooser desk accessory............................................ 23Classes command ................................................... 256Clear All Breakpoints command ............................ 248Clear command .............................................. 243, 264Clear menu command....................................... 24, 164Clipboard.................................................... 17, 24, 163
in a separate window........................................... 24Close box ...................................................... 185, 186Close command.............................................. 242, 263Close menu command .............................................. 22Code command....................................................... 257Code For................................................................. 250code window .......................................................... 257colon, in path names............................................... 131color Quickdraw example ......................... 206Command-Enter ..................................................... 162Command-key equivalent......................................... 19Commando command............................................... 62commando interface ................................................. 62Commando interface .................................... 12, 38, 72Command-Period
termination .................................................. 83, 101Command-Period
checking ............................................................ 161key ........................................................................ 3
Command-Return ................................................... 162COMMON blocks from C...................................... 212COMMON, aligning data....................................... 109compatibility, introduction ......................................... 3compiler directives ................................................... 94
FIXED directive.................................................. 95FREE directive.................................................... 95NAME directive.................................................. 95STACK directive ................................................ 96
compiler options..................................................... 267-!N61, use temporary files ................................ 114-8, Fortran 90 .................................................... 107-A, ANSI C ....................................................... 113-A, suppress alignment warnings ........................ 97-align, use 68k alignment .................................. 116-appleext off, suppress Apple extensions .......... 116-C, check boundaries........................................... 98-c, object files.................................................... 101-char, make chars unsigned ............................... 117-D, define compiler variable ............................. 101-d, define preprocessor variable ........................ 118-d, one trip DO loops......................................... 106
Index
Fortran User Guide
-E, preprocess to stdout .....................................119-ea , stop on error.................................................84-ej, one trip DO loops ..........................................88-en, non-standard usage .......................................84-enum, use int enums.........................................116-ep, demote Double Precision..............................87-eq, allow greater than 100 errors........................84-eR, default recursion ..........................................84-except, exception handling...............................114-f, case fold................................................105, 121-f, fixed source form............................................87-f, freed source form............................................87-F, temporary files ...............................84, 101, 275-g, debug..............................................................79-g, Fx debugging..........................................98, 121-gmin, Fx debugging ...........................................98-H, include tree to stderr....................................119-H, max lines to unroll.......................................103-h, unroll count ..................................................103-I, INCLUDE path...............................................74-i, integer sizes.............................................88, 106-I, MODULE file .................................................90-init, set initialization prefix ..............................117-inline none, no inlines ......................................114-K, escape sequences ...................................92, 109-K, K&R C ........................................................113-m, delayed stores................................................99-M, extern globals..............................................106-maxerr, max errors ...........................................115-N1, static storage......................................105, 109-N102, zero extend INTEGER*1 ......................106-N109, case fold ................................................105-N11, 32 bit branches ....................................83, 98-N110, no Common mangling ...........................111-N111, debugging structures................................99-N112, IBM VS Free-Form ...............................107-N113, floating point sizes ..........................87, 109-N114, warnings for undeclared variables.........111-N115, pad source lines .....................................111-N124, procedure trace ................................98, 114-N15, append underscore...................................110-N16, UNIT specifier.........................................109-N17,Pascal function .........................................110-N18, function decomposition ...........................103-N18, use long branches ....................................113-N2, double precision ........................................108-N20, left-to-right ..............................................108-N21, Pascal keyword........................................110-N22, set Common name...................................107-N26, set big-endian ..........................................107-N27, set little-endian ........................................107-N3, record lengths ............................................105-N32, non-ANSI ................................................106-N34, align COMMON .....................................109-N4, CASE DEFAULT .....................................109-N5, treat DATA as constants............................102-N51, 32 bit RECL ............................................105-N57, align structure fields to 2-byte boundaries;
.............................................................110, 111-N58, align structure fields to 4-byte boundaries;
.....................................................................111-N59, align structure fields to 8-byte boundaries;
.....................................................................111
-N7, sign extend................................................ 109-N80, procedure trace ......................................... 85-N9, Command-Period................................ 83, 101-O, basic optimizations ............................... 86, 102-o, executable name .................................... 78, 101-O, optimize ........................................................ 79-p, MODULE path .............................................. 90-P, preprocess to file ......................................... 119-p, profiling................................................. 98, 114-profile, profiling ................................................ 85-ptv, verbose templates ..................................... 119-q, quiet............................................................. 119-q, quiet............................................................. 100-Q51, no fma instructions ................................. 108-Rb, check array conformance ............................ 93-Rb, check boundaries......................................... 93-Rp, check pointers ............................................. 93-Rs, check substrings .......................................... 93-s, static storage ...........................87, 105, 121, 130-std, draft std C++............................................. 113-T, max internal handle................................. 89, 99-t, temporary strings.................................... 89, 110-term, set termination prefix ............................. 117-Tp, ARM C++ ................................................. 112-U, loop unrolling ............................................. 103-u, undefine preprocessor variable .................... 118-v , show progress ....................................... 83, 100-V , show version ................................................ 84-V, VAX Tab-Format ....................................... 107-v, verbose ........................................................ 119-W, line length .................................................... 87-w, suppress compiler warnings.................... 83, 97-W, wide format................................................ 107-w1, suppress template warnings ...................... 115-w16, suppress warnings................................... 115-w31, suppress all warnings.............................. 115-w8, suppress anachronism warnings................ 115-w8, suppress informational warnings .............. 115-wabort, treat all warnings as errors.................. 115-wp, treat anachronisms as errors...................... 115-x , disable compiler directive............................. 88-x, conditional compilation ................................. 99-YCOM_NAMES, COMMON block case ......... 92-YCOM_PFX, COMMON block prefix ............. 92-YCOM_SFX, COMMON block suffix.............. 92-YDEALLOC, cache control .............................. 94-YEXT_NAMES, external names....................... 93-YEXT_SFX, external symbol suffix ................. 93-YNDFP, type elements ...................................... 92-z, suppress messages ......................................... 85-Z, suppress warning number.............................. 85
Compiler Options....................................228, 260, 265compiler version....................................................... 84compiling Fortran source............................................ 9complex data types
equivalent declarations in C.............................. 207in Pascal............................................................ 213
conditional compilation............................................ 99conditional compilation variables .......................... 101Configure command........................................253, 262Confirm command ................................................... 64constant propagation .............................................. 102continuation lines ................................................... 122
Language Systems Fortran Extensions 3
Fortran User Guide
Continue command .................................................246Control menu ..........................................................246conventions used in the manual ..................................3Copy command ...............................................243, 264Copy menu command .......................................24, 163could not launch error ...............................................16Create Build Commands… .........................144, 145creating a new text file..............................................21current folder ....................................................79, 189cursor example ...............................................206Cut command..................................................243, 264Cut menu command ..........................................24, 163data initialization to zero.........................................105DATA treated as constants .....................................102Date command ..........................................................59date example....................................................206DATE subroutine ....................................................122debugging ...........................................98, 99, 111, 225
array bounds checking .........................................98conditional compilation .......................................99
DebugServices for PowerPC...................................231delayed stores............................................................99Delete command .......................................................48deleting Worksheet text ............................................80DeRez tool ..............................................................152Descending command.............................................266Dev
Null ...................................................................40StdErr...............................................................40
diagnostic output.......................................................40Differences..............................................................287differences, between Absoft Fortran 77 versions....289Directory command ............................................60, 79Directory menu ...................................................30, 79Directory menu or by entering the following line in
the Worksheet:...................................................189display compiler alignment warning messages .........97Display Selection menu command............................27distribution issues ...................................................128divide by zero exceptions........................................134DO loops
one trip...............................................................106DO Loops..................................................................88documentation conventions.........................................3double colon............................................................132double precision
functions ............................................................108Down command......................................................247dynamic memory allocation....................................131Edit menu..................................................23, 242, 264Editing commands
Edit menu.............................................................23File menu .............................................................21Find menu............................................................25Mark menu...........................................................29
editing files .................................................................9eject command ...................................................40Eject command .........................................................49enabling the exception ............................................134Enabling/Disabling Menu Items .............................170end-of-file character................................................162Enter key...................................................................20Enter key.....................................................................2
Entire Word............................................................. 26error messages .................................................. 80, 275errors ........................................................................ 84
at runtime .......................................................... 123escape sequences in strings .................................... 109event loop............................................................... 166example programs .................................................. 206
DateTime.f................................................... 206Hello.f90 ............................................................. 13MRWE source code .................................... 206plotting ....................................................... 206printing ....................................................... 206
exceptionsdivide by zero.................................................... 134operand error..................................................... 134overflow............................................................ 134
executable name, specifying ............................ 78, 101extensions
key Microsoft FORTRAN................................. 124key Sun FORTRAN ones.................................. 126key VAX FORTRAN ones ............................... 121key VS FORTRAN ones................................... 123
extensions to FORTRAN 77 ...................................... 3f77 tool ................................................................... 136f77 tool options
-appl, application with MRWE ......................... 138-link, options for linker ..................................... 138-plainappl, generate application ........................ 137-tool, generate a tool ......................................... 138
f77fe tool ................................................................ 136f77init.o startup ...................................................... 195F90Includes folder.................................................. 192FExamples folder ................................................... 206file
markers................................................................ 29names ................................................................ 131
Filecommand............................................................. 68creator ............................................................... 187menu ................................................................... 21type ................................................................... 187
FILE ...................................................................... 132File menu........................................................ 241, 263Files command ......................................................... 47FIncludes folder ..................................................... 192Find Again command ............................................. 251Find command........................................................ 251Find line numbers..................................................... 25Find menu................................................................. 25Find menu command................................................ 25Find Same menu command ...................................... 27Find Selection menu command ................................ 27Finder
icons.......................................................... 153, 222Finder information
example.......................................................... 206FIXED directive ....................................................... 95floating point
unit .................................................................... 133floating point unit
exception handling ............................................ 134rounding direction............................................. 134
Flush command ........................................................ 49
Index
Fortran User Guide
fold to lower case....................................................105font name ..................................................................43font size ....................................................................43Force Quit ..............................................................161FORM='BINARY' specifier ...................................125Format command ..................................................133Format menu command ............................................24Fortran 77
introduction ...........................................................1options .................................................................96
FORTRAN 77 extensions3, 99, 105, 106, 107, 109,110COMPLEX size.................................................109conditional compilation .......................................99escape sequences ...............................................109Fortran 90 Free Source Form.............................107IBM VS Free Form............................................107INTEGER size...................................................106LOGICAL size ..................................................106lower case..........................................................105one trip DO........................................................106REAL size .........................................................109REPEAT
function ........................................................110upper case..........................................................105VAX Tab-Format ..............................................107wide source format ............................................107
FORTRAN 77 interface files ..................................192Fortran 90
options .................................................................82Fortran 90 Fixed Source Form..................................87Fortran 90 Free Source Form............................87, 107Fortran 90 interface files.........................................192FORTRAN math routines
calling from C............................................211, 219FPU Registers command ........................................259FREE directive .........................................................95FREF resource ................................................154, 223frequent Command-Period checks ....................83, 101fsplit utility .............................................................275Fsplit utility tool .....................................................138FTNCHEK utility tool ............................................139full path name .........................................................131function
call to C from FORTRAN .................................210call to FORTRAN from C .................................211call to FORTRAN from Pascal..........................218call to Pascal from FORTRAN..........................218decomposition ...................................................103
Fx 98, 111General Registers command ...................................258Get Info command ..................................................129GetFileName command ............................................64GLOBAL................................................................106graying of text.............................................................3handle .....................................................................199
example ..........................................................206Hello.f90 file.............................................................13Help command..........................................................58help for MPW commands .........................................11HEXA resource.......................................................158
in MPW .............................................................131hexa tool .................................................................158
Hide Calls command.............................................. 265Hide Graph command ............................................ 265Hide Time command.............................................. 264Hide Time/Call command ...................................... 265Hide/Show Toolbar command ............................... 254hierarchical folder structure ................................... 132Home command ..................................................... 247IBM RS/6000, porting from................................... 127icon, application..............................................153, 222IDATE subroutine.................................................. 122IEEE floating point math ....................................... 133IMPLICIT NONE statement .................................. 195IMSL library ............................................................ 76INCLUDE files
for resources...............................................153, 222toolbox dependencies........................................ 192
INCLUDE path ........................................................ 74include tree to stderr............................................... 119Info command ........................................................ 263initialization routines.............................................. 195input from keyboard............................................... 162Inside Macintosh .................................................... 190INTEGER, 2-byte default ...................................... 106INTEGER, 8-byte default ...................................... 106Intel 386, porting from ........................................... 127interface files.......................................................... 192interfacing FORTRAN and C
calling FORTRAN math routines ..............211, 219compatible type declarations ............................ 207function call to C from FORTRAN .................. 210function call to FORTRAN from C .................. 211function results.................................................. 210LOC function .................................................... 210passing an array ................................................ 210passing pointers ................................................ 208passing strings................................................... 211passing values ................................................... 208reference parameters ......................................... 208
passing to C ................................................. 209passing to FORTRAN ................................. 208
VAL function.................................................... 209value parameters ............................................... 209
interfacing FORTRAN and Pascalcall to FORTRAN from Pascal ......................... 218call to Pascal from FORTRAN ......................... 218compatible type declarations ............................ 213function results.................................................. 218passing strings................................................... 219passing values ................................................... 216reference parameters ......................................... 216
passing to FORTRAN ................................. 216passing to Pascal.......................................... 216
VAL function.................................................... 217value parameters ............................................... 217
intermediate files.............................................. 84, 101intrinsic functions
LOC .................................................................. 210math ...........................................................211, 219VAL...........................................................209, 217
italicized text, defined................................................ 3keyboard input ....................................................... 162Kill command......................................................... 246Language Systems Fortran..............................127, 291
Language Systems Fortran Extensions 5
Fortran User Guide
LAPACK library.......................................................77large applications ............................................156, 224Launching OTHER APPLICATIONS ....................171left-to-right operator evaluation ..............................108license for redistribution .........................................128Line command ..................................................67, 249linefeed character, changing ...................................126linefeed character, removing...................................125Linker Options ................................................230, 261Literal .......................................................................26Lnk tool...................................................................150LOC, intrinsic function ...........................................210local variables .........................................................158Locals command .....................................................249LONG sign extension .............................................109loop unrolling..........................................................103MacFortran .............................................................128MacFortran II..........................................................128MacFortran/020 ......................................................128MacFortran/AUX....................................................128Macintosh Programmer’s Workshop (MPW) .............2Macintosh toolbox ......................................................4Macintosh User Interface, ...........................................9make chars unsigned ...............................................117makefile tutorial ......................................................149Mark command .........................................................62Mark menu................................................................29Mark menu command ...............................................29markers, text .............................................................29master pointer .........................................................199math routines
FORTRAN ................................................211, 219max errors ...............................................................115Memory command..................................................257memory management..............................................129Memory Management.............................................158menu
adding ................................................................167checkmarks ........................................................170deleting ..............................................................169deleting an item .................................................169is blank error......................................................130item, enabling and disabling ..............................170
menusApple ...................................................................23Edit ......................................................................23File.......................................................................21Find......................................................................25Mark ....................................................................29Tools....................................................................72Window ...............................................................30
MenusDirectory..............................................................30
metacommands, Microsoft FORTRAN ..................125Microsoft FORTRAN
metacommands ..................................................125porting from.......................................................124
Mixed Mode Manager.............................................197modifier keys ..............................................................3MODULE .................................................................90MODULE file ...........................................................90MODULE path .........................................................90Move command ........................................................49
MoveWindow command .......................................... 69MPW
documents ............................................................. 9Shell ...................................................................... 2Shell icon .............................................................. 9Worksheet ........................................................... 33
MPW commands ...................................................... 46MPW stack size...................................................... 158MRWE ............................................................. 83, 101
adding an icon........................................... 154, 223and the toolbox.................................................. 196basics................................................................... 16customization .................................................... 164Event Loop........................................................ 166programming..................................................... 164source code ................................................ 206
MRWE.o file .......................................................... 159mrwe_AddMenu ................................................... 167mrwe_DoMenu ..................................................... 169MS-DOS files, translating ...................................... 125MS-DOS, porting from........................................... 124Multiple Windows.................................................. 182munch..................................................................... 117-N9 ......................................................................... 161NAME directive ....................................................... 95New Assembly command....................................... 241New menu command................................................ 21New Source command............................................ 241NewFolder command ............................................... 47Next command ....................................................... 249Next Error menu command ...................................... 28NeXT, porting from................................................ 126NLS message catalogs.............................................. 43no inlines ................................................................ 114non ANSI warnings ................................................ 106null device ................................................................ 40object files, generating ........................................... 101off-screen bitmap example .................... 206On command .................................................. 253, 262one trip DO............................................................. 106open additional windows........................................ 182Open command .............................................. 241, 263Open menu command............................................... 22Open Selection menu command............................... 22OPEN statement ..................................................... 132Open Workspace command.................................... 241operand error exceptions ........................................ 134operator evaluation................................................. 108optimization...................................................... 85, 102
basic optimization ....................................... 86, 102constant propagation ......................................... 102function decomposition..................................... 103
optimizationsloop unrolling.................................................... 103
options.................................................................... 267Options
Compilers.................................................. 228, 260Linker........................................................ 230, 261
options, manual convention........................................ 3other porting issues................................................. 128output redirection ..................................................... 40overflow exceptions ............................................... 134Page Setup command ............................................. 263
Index
Fortran User Guide
page setup dialog ....................................................163Page Setup menu command......................................23partial path name ....................................................131Pascal
function results ..................................................218interfacing with FORTRAN(see interfacing
FORTRAN and Pascal)Pascal function........................................................110passing arguments to toolbox .................................193Paste command ...............................................243, 264Paste menu command .......................................24, 164path names ..............................................................131pause after the program ends ..................................185PenState structure ...................................................197plotting example ..........................................206pointer, passing to toolbox......................................197Pointers ................................................... 237, 251, 252porting code ............................................................121
doesn’t run correctly;.........................................123from IBM RS/6000............................................127from Intel 386....................................................127from Microsoft FORTRAN ...............................124from MS-DOS ...................................................124from NeXT ........................................................126from SCO Unix .................................................127from Sparc .........................................................126from Sun FORTRAN ........................................126from VAX FORTRAN ......................................121from VS FORTRAN..........................................123
PPCTraceEnabler....................................................231preconnected units ..................................................160Preferences command.............................................243preprocess to file.....................................................119preprocess to stdout ................................................119preprocessor variables ............................................118Prev command ........................................................249Previous menu command..........................................28Print ........................................................ 237, 251, 252Print * .............................................................251, 252Print As command ..........................................252, 253Print command..................................................67, 263Print menu command................................................23printing example ..........................................206Profile menu ...........................................................253profiling ...................... 85, 98, 114, 226, 228, 253, 262profmt .....................................................................254Profmt .....................................................................262qualifiers, VAX FORTRAN ...................................122Quickdraw Globals .................................................201Quickdraw.inc file ..................................................192quiet ........................................................................119Quit command ..........................................65, 242, 264Quit menu command.........................................23, 163RAN function .........................................................122random numbers...............................................206Receiving Apple Events .........................................176RECL
for 32-bit words .................................................105RECORD statement........................................196, 197redirection of output .................................................40removing linefeed character....................................125Rename command ....................................................50Replace menu command...........................................28
Replace Same menu command ................................ 28Request command .................................................... 63Required Apple Events .......................................... 174resource compiler............................................136, 221resource description file ..........................136, 151, 221resource editor.................................................136, 221resource include files ......................................153, 222resources ................................................................ 221Restart command.................................................... 246Return command .................................................... 246Return key............................................................ 2, 20Revert to Saved menu command.............................. 23Rez include files....................................................... 43Rez tool .................................................................. 151RIncludes folder..............................................153, 222road maps................................................................... 4routing command output .......................................... 39RS/6000, porting from ........................................... 127Run To command................................................... 247runtime error messages .......................................... 275runtime error messages .......................................... 123Runtime preferences .............................................. 184Save a Copy menu command................................... 23Save As menu command.......................................... 23Save menu command ............................................... 22SAVE statements ................................................... 158Save Window Positions command ......................... 242Save Workspace command .................................... 242saveOnClose ..................................................... 185saving Worksheet text .............................................. 80SCO Unix, porting from......................................... 127scope ...............................................................239, 248script files................................................................. 43scriptable application ............................................. 181Search command ...................................................... 52SECNDS subroutine............................................... 122Select All command ............................................... 243Select All command ................................................. 80Select All menu command ....................................... 24Selection Expression............................................. 26Sending Apple Events .......................................... 175Set Breakpoint On.................................................. 253Set command............................................................ 60Set current directory........................................... 31, 79Set Directory menu command............................ 31, 79set initialization prefix ........................................... 117set termination prefix ............................................. 117SetCurs.f example .................................................. 200SetDirectory command ...................................... 61, 79SetFile command...................................................... 51SetPrefs
Tool................................................................... 184SetPrefs Tool.......................................................... 184setting tab size........................................................ 133setting window to 72 columns................................ 133shared data ............................................................. 106shared libraries ....................................................... 287Shift menu commands.............................................. 25Show Clipboard menu command ............................. 24show compiler progress.................................... 83, 100Show Directory menu command.............................. 31Show Program Counter command ......................... 248Shutdown command................................................. 65
Language Systems Fortran Extensions 7
Fortran User Guide
single stepping ........................................................234SIZE resource .........................................155, 186, 224
setting ................................................................129SIZE(-1) resource ...................................................230SizeWindow command .............................................69skip count........................................................236, 255Sort menu................................................................265source line length ......................................................87Sparc, Absoft compiler for......................................126Sparc, porting from .................................................126spooling example ..........................................206square brackets, defined..............................................3Stack command.......................................................259STACK directive ......................................................96Stack window..........................................................240Stack Windows menu command...............................30standard file dialog..................................................132standard file example ..............................206standard output..........................................................40
suppressing ........................................................100startup documents ...................................................275startup initialization ................................................195static storage .............................................87, 105, 158Statics command .............................................249, 250Step Into command .................................................247Step Over command................................................247Stop command ........................................................246stop program execution...........................................161string length ......................................................89, 110strings
passing FORTRAN to C....................................211passing FORTRAN to Pascal ............................219
STRUCTURE fields, aligning ........................110, 111STRUCTURE statement .........................................196Sun FORTRAN, porting from.................................126support ....................................................................285suppress all warning messages................................115suppress anachronism warning messages................115suppress Apple extensions ......................................116suppress delayed stores .............................................99suppress informational warning messages ..............115suppress list of compiler warning messages........83, 97suppress template warning messages ......................115suppress warning messages.....................................115switching between applications ..............................161Symbols command..................................................259Symbols window.....................236, 249, 250, 252, 259System 6 notes ........................................................276System 7..................................................................161system errors ...........................................................158tab character............................................................133tab size ......................................................................25TABSIZE variable ..................................................138Target command .......................................................67technical support .....................................................285Text characteristics .................................................186text markers ..............................................................29text, not displayed...................................................130Tile command .........................................................254Tile Windows menu command .................................30TileWindows command ............................................68time example....................................................206TIME subroutine.....................................................122
timer interval .......................................................... 187tool arguments example ........................... 206toolbox example programs ..................................... 206Tools menu............................................................... 72tracing......................................................... 85, 98, 114treat all warnings as errors...................................... 115treat anachronisms as errors ................................... 115tutorial
books for beginners........................................... 282compiling with Commando................................. 13
Types command ..................................................... 250Unable to swap tool segment................ 275underlined text, defined.............................................. 3underscores in routine names ................................. 110Undo command .............................................. 243, 264Undo menu command ...................................... 23, 163UNIT specifier ....................................................... 109Universal Procedure Pointers ......................... 197, 198Unix compatibility library........................................ 76Unix files, translating ............................................. 126Unmark command .................................................... 62Unmark menu command .......................................... 29UnSet command ....................................................... 60Up command .......................................................... 248use 68k alignment................................................... 116use int enums.......................................................... 116use long branches ................................................... 113use temporary files ................................................. 114using compiled applications ....................................... 9using the toolbox .................................................... 190Vaccine................................................................... 275VAL function ......................................................... 193VALUE statement .................................. 193, 209, 217variables ......................................................... 236, 240variables, environment ............................................. 42VAX FORTRAN
porting from ...................................................... 121qualifiers ........................................................... 122
VAX Tab-Format source........................................ 107VAX/VMS compatibility library.............................. 76verbose ................................................................... 119verbose templates ................................................... 119View As command ................................................. 250View current directory ............................................. 31View menu ............................................................. 248virus detectors ........................................................ 275Volumes command................................................... 50VS FORTRAN, porting from................................. 123warn of non-ANSI usage........................................ 106warning messages..................................................... 80Watch *, ................................................................. 252Watch All command............................................... 252Watch Locals command ......................................... 253WhereIs command.................................................... 49whetstone benchmark................................... 206wide source format ................................................. 107Window characteristics .......................................... 185Window menu .......................................................... 30Window name....................................................... 185Windows command.................................................. 68Windows menu....................................................... 254WORD sign extension............................................ 109Worksheet, deleting text........................................... 80
Index
Fortran User Guide
Y2K bug .....................................................................7ZoomWindows command.........................................68
Σ symbol .................................................................. 40