Document Details

ContrastyAutoharp

Uploaded by ContrastyAutoharp

Tags

GNU Fortran Fortran programming Compiler Computer programming

Summary

This document is a user manual for GNU Fortran, a compiler for the Fortran programming language, describing its command options, runtime, language reference, extensions, and interoperability features. It's a comprehensive guide for those working with Fortran programming.

Full Transcript

Using GNU Fortran For gcc version 4.5.2 (GCC) The gfortran team Published by the Free Software Foundation 51 Franklin Street, Fifth Floor Boston, MA 02110-1301, USA Copyright c 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,...

Using GNU Fortran For gcc version 4.5.2 (GCC) The gfortran team Published by the Free Software Foundation 51 Franklin Street, Fifth Floor Boston, MA 02110-1301, USA Copyright c 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with the Invariant Sections being “Funding Free Software”, the Front-Cover Texts being (a) (see below), and with the Back-Cover Texts being (b) (see below). A copy of the license is included in the section entitled “GNU Free Documentation License”. (a) The FSF’s Front-Cover Text is: A GNU Manual (b) The FSF’s Back-Cover Text is: You have freedom to copy and modify this GNU Manual, like GNU software. Copies published by the Free Software Foundation raise funds for GNU development. i Short Contents 1 Introduction......................................... 1 Part I: Invoking GNU Fortran.............................. 5 2 GNU Fortran Command Options........................ 7 3 Runtime: Influencing runtime behavior with environment variables........................................... 25 Part II: Language Reference.............................. 29 4 Fortran 2003 and 2008 Status.......................... 31 5 Compiler Characteristics.............................. 33 6 Extensions.......................................... 35 7 Mixed-Language Programming......................... 47 8 Intrinsic Procedures.................................. 55 9 Intrinsic Modules................................... 185 Contributing........................................... 189 GNU General Public License.............................. 193 GNU Free Documentation License......................... 205 Funding Free Software................................... 213 Option Index.......................................... 215 Keyword Index......................................... 217 iii Table of Contents 1 Introduction..................................... 1 1.1 About GNU Fortran........................................... 1 1.2 GNU Fortran and GCC........................................ 2 1.3 Preprocessing and conditional compilation...................... 2 1.4 GNU Fortran and G77......................................... 3 1.5 Project Status................................................. 3 1.6 Standards...................................................... 4 1.6.1 Varying Length Character Strings......................... 4 Part I: Invoking GNU Fortran.................... 5 2 GNU Fortran Command Options............. 7 2.1 Option summary............................................... 7 2.2 Options controlling Fortran dialect............................. 8 2.3 Enable and customize preprocessing........................... 10 2.4 Options to request or suppress errors and warnings............ 13 2.5 Options for debugging your program or GNU Fortran.......... 16 2.6 Options for directory search................................... 17 2.7 Influencing the linking step.................................... 17 2.8 Influencing runtime behavior.................................. 17 2.9 Options for code generation conventions....................... 18 2.10 Environment variables affecting gfortran.................... 23 3 Runtime: Influencing runtime behavior with environment variables........................ 25 3.1 GFORTRAN_STDIN_UNIT—Unit number for standard input...... 25 3.2 GFORTRAN_STDOUT_UNIT—Unit number for standard output.... 25 3.3 GFORTRAN_STDERR_UNIT—Unit number for standard error...... 25 3.4 GFORTRAN_USE_STDERR—Send library output to standard error............................................................... 25 3.5 GFORTRAN_TMPDIR—Directory for scratch files.................. 25 3.6 GFORTRAN_UNBUFFERED_ALL—Don’t buffer I/O on all units..... 25 3.7 GFORTRAN_UNBUFFERED_PRECONNECTED—Don’t buffer I/O on preconnected units............................................. 25 3.8 GFORTRAN_SHOW_LOCUS—Show location for runtime errors...... 25 3.9 GFORTRAN_OPTIONAL_PLUS—Print leading + where permitted.. 26 3.10 GFORTRAN_DEFAULT_RECL—Default record length for new files............................................................... 26 3.11 GFORTRAN_LIST_SEPARATOR—Separator for list output........ 26 3.12 GFORTRAN_CONVERT_UNIT—Set endianness for unformatted I/O............................................................... 26 3.13 GFORTRAN_ERROR_DUMPCORE—Dump core on run-time errors.. 27 iv The GNU Fortran Compiler 3.14 GFORTRAN_ERROR_BACKTRACE—Show backtrace on run-time errors............................................................... 27 Part II: Language Reference..................... 29 4 Fortran 2003 and 2008 Status................ 31 4.1 Fortran 2003 status........................................... 31 4.2 Fortran 2008 status........................................... 32 5 Compiler Characteristics..................... 33 5.1 KIND Type Parameters....................................... 33 5.2 Internal representation of LOGICAL variables................. 33 6 Extensions..................................... 35 6.1 Extensions implemented in GNU Fortran...................... 35 6.1.1 Old-style kind specifications.............................. 35 6.1.2 Old-style variable initialization........................... 35 6.1.3 Extensions to namelist................................... 36 6.1.4 X format descriptor without count field................... 37 6.1.5 Commas in FORMAT specifications......................... 37 6.1.6 Missing period in FORMAT specifications................... 37 6.1.7 I/O item lists............................................ 37 6.1.8 BOZ literal constants..................................... 37 6.1.9 Real array indices........................................ 38 6.1.10 Unary operators........................................ 38 6.1.11 Implicitly convert LOGICAL and INTEGER values.......... 38 6.1.12 Hollerith constants support.............................. 38 6.1.13 Cray pointers........................................... 39 6.1.14 CONVERT specifier........................................ 41 6.1.15 OpenMP................................................ 41 6.1.16 Argument list functions %VAL, %REF and %LOC............ 42 6.2 Extensions not implemented in GNU Fortran.................. 42 6.2.1 STRUCTURE and RECORD................................... 43 6.2.2 ENCODE and DECODE statements........................... 44 6.2.3 Variable FORMAT expressions.............................. 44 v 7 Mixed-Language Programming............... 47 7.1 Interoperability with C........................................ 47 7.1.1 Intrinsic Types........................................... 47 7.1.2 Derived Types and struct................................. 47 7.1.3 Interoperable Global Variables............................ 48 7.1.4 Interoperable Subroutines and Functions.................. 48 7.1.5 Further Interoperability of Fortran with C................ 50 7.2 GNU Fortran Compiler Directives............................. 50 7.3 Non-Fortran Main Program................................... 51 7.3.1 _gfortran_set_args — Save command-line arguments... 51 7.3.2 _gfortran_set_options — Set library option flags....... 51 7.3.3 _gfortran_set_convert — Set endian conversion........ 52 7.3.4 _gfortran_set_record_marker — Set length of record markers.................................................... 53 7.3.5 _gfortran_set_fpe — Set when a Floating Point Exception should be raised............................................ 53 7.3.6 _gfortran_set_max_subrecord_length — Set subrecord length...................................................... 54 8 Intrinsic Procedures........................... 55 8.1 Introduction to intrinsic procedures........................... 55 8.2 ABORT — Abort the program.................................. 55 8.3 ABS — Absolute value......................................... 56 8.4 ACCESS — Checks file access modes............................ 56 8.5 ACHAR — Character in ASCII collating sequence................ 57 8.6 ACOS — Arccosine function.................................... 58 8.7 ACOSH — Inverse hyperbolic cosine function.................... 58 8.8 ADJUSTL — Left adjust a string............................... 59 8.9 ADJUSTR — Right adjust a string.............................. 59 8.10 AIMAG — Imaginary part of complex number................. 60 8.11 AINT — Truncate to a whole number......................... 60 8.12 ALARM — Execute a routine after a given delay............... 61 8.13 ALL — All values in MASK along DIM are true.............. 62 8.14 ALLOCATED — Status of an allocatable entity................. 63 8.15 AND — Bitwise logical AND.................................. 63 8.16 ANINT — Nearest whole number.............................. 64 8.17 ANY — Any value in MASK along DIM is true............... 64 8.18 ASIN — Arcsine function..................................... 65 8.19 ASINH — Inverse hyperbolic sine function..................... 66 8.20 ASSOCIATED — Status of a pointer or pointer/target pair..... 66 8.21 ATAN — Arctangent function................................. 68 8.22 ATAN2 — Arctangent function................................ 68 8.23 ATANH — Inverse hyperbolic tangent function................. 69 8.24 BESSEL_J0 — Bessel function of the first kind of order 0...... 69 8.25 BESSEL_J1 — Bessel function of the first kind of order 1...... 70 8.26 BESSEL_JN — Bessel function of the first kind................ 70 8.27 BESSEL_Y0 — Bessel function of the second kind of order 0... 71 8.28 BESSEL_Y1 — Bessel function of the second kind of order 1... 72 vi The GNU Fortran Compiler 8.29 BESSEL_YN — Bessel function of the second kind............. 72 8.30 BIT_SIZE — Bit size inquiry function........................ 73 8.31 BTEST — Bit test function................................... 73 8.32 C_ASSOCIATED — Status of a C pointer....................... 74 8.33 C_FUNLOC — Obtain the C address of a procedure............ 74 8.34 C_F_PROCPOINTER — Convert C into Fortran procedure pointer............................................................... 75 8.35 C_F_POINTER — Convert C into Fortran pointer.............. 76 8.36 C_LOC — Obtain the C address of an object.................. 76 8.37 C_SIZEOF — Size in bytes of an expression................... 77 8.38 CEILING — Integer ceiling function........................... 78 8.39 CHAR — Character conversion function....................... 78 8.40 CHDIR — Change working directory.......................... 79 8.41 CHMOD — Change access permissions of files................... 79 8.42 CMPLX — Complex conversion function....................... 80 8.43 COMMAND_ARGUMENT_COUNT — Get number of command line arguments..................................................... 81 8.44 COMPLEX — Complex conversion function..................... 81 8.45 CONJG — Complex conjugate function........................ 82 8.46 COS — Cosine function....................................... 83 8.47 COSH — Hyperbolic cosine function........................... 83 8.48 COUNT — Count function..................................... 84 8.49 CPU_TIME — CPU elapsed time in seconds.................... 85 8.50 CSHIFT — Circular shift elements of an array................. 85 8.51 CTIME — Convert a time into a string........................ 86 8.52 DATE_AND_TIME — Date and time subroutine................. 87 8.53 DBLE — Double conversion function.......................... 88 8.54 DCMPLX — Double complex conversion function............... 88 8.55 DFLOAT — Double conversion function........................ 89 8.56 DIGITS — Significant binary digits function.................. 89 8.57 DIM — Positive difference.................................... 90 8.58 DOT_PRODUCT — Dot product function........................ 90 8.59 DPROD — Double product function............................ 91 8.60 DREAL — Double real part function........................... 92 8.61 DTIME — Execution time subroutine (or function)............ 92 8.62 EOSHIFT — End-off shift elements of an array................ 93 8.63 EPSILON — Epsilon function................................. 94 8.64 ERF — Error function........................................ 95 8.65 ERFC — Error function....................................... 95 8.66 ERFC_SCALED — Error function............................... 96 8.67 ETIME — Execution time subroutine (or function)............ 96 8.68 EXIT — Exit the program with status........................ 97 8.69 EXP — Exponential function................................. 97 8.70 EXPONENT — Exponent function.............................. 98 8.71 FDATE — Get the current time as a string.................... 98 8.72 FLOAT — Convert integer to default real...................... 99 8.73 FGET — Read a single character in stream mode from stdin.. 100 8.74 FGETC — Read a single character in stream mode............ 100 vii 8.75 FLOOR — Integer floor function.............................. 101 8.76 FLUSH — Flush I/O unit(s)................................. 102 8.77 FNUM — File number function............................... 102 8.78 FPUT — Write a single character in stream mode to stdout... 103 8.79 FPUTC — Write a single character in stream mode........... 103 8.80 FRACTION — Fractional part of the model representation.... 104 8.81 FREE — Frees memory...................................... 105 8.82 FSEEK — Low level file positioning subroutine............... 105 8.83 FSTAT — Get file status..................................... 106 8.84 FTELL — Current stream position........................... 107 8.85 GAMMA — Gamma function.................................. 107 8.86 GERROR — Get last system error message.................... 108 8.87 GETARG — Get command line arguments.................... 108 8.88 GET_COMMAND — Get the entire command line............... 109 8.89 GET_COMMAND_ARGUMENT — Get command line arguments.... 110 8.90 GETCWD — Get current working directory.................... 111 8.91 GETENV — Get an environmental variable.................... 111 8.92 GET_ENVIRONMENT_VARIABLE — Get an environmental variable.............................................................. 112 8.93 GETGID — Group ID function............................... 112 8.94 GETLOG — Get login name.................................. 113 8.95 GETPID — Process ID function.............................. 113 8.96 GETUID — User ID function................................. 113 8.97 GMTIME — Convert time to GMT info....................... 114 8.98 HOSTNM — Get system host name........................... 115 8.99 HUGE — Largest number of a kind........................... 115 8.100 HYPOT — Euclidean distance function...................... 115 8.101 IACHAR — Code in ASCII collating sequence................ 116 8.102 IAND — Bitwise logical and................................ 116 8.103 IARGC — Get the number of command line arguments...... 117 8.104 IBCLR — Clear bit......................................... 118 8.105 IBITS — Bit extraction.................................... 118 8.106 IBSET — Set bit........................................... 118 8.107 ICHAR — Character-to-integer conversion function.......... 119 8.108 IDATE — Get current local time subroutine (day/month/year).............................................................. 120 8.109 IEOR — Bitwise logical exclusive or........................ 120 8.110 IERRNO — Get the last system error number............... 121 8.111 INDEX — Position of a substring within a string............ 121 8.112 INT — Convert to integer type............................. 122 8.113 INT2 — Convert to 16-bit integer type..................... 122 8.114 INT8 — Convert to 64-bit integer type..................... 123 8.115 IOR — Bitwise logical or................................... 123 8.116 IRAND — Integer pseudo-random number................... 124 8.117 IS_IOSTAT_END — Test for end-of-file value................ 124 8.118 IS_IOSTAT_EOR — Test for end-of-record value............. 125 8.119 ISATTY — Whether a unit is a terminal device.............. 125 8.120 ISHFT — Shift bits........................................ 126 viii The GNU Fortran Compiler 8.121 ISHFTC — Shift bits circularly............................. 126 8.122 ISNAN — Test for a NaN................................... 127 8.123 ITIME — Get current local time subroutine (hour/minutes/seconds)...................................... 127 8.124 KILL — Send a signal to a process......................... 128 8.125 KIND — Kind of an entity.................................. 128 8.126 LBOUND — Lower dimension bounds of an array............ 129 8.127 LEADZ — Number of leading zero bits of an integer......... 129 8.128 LEN — Length of a character entity........................ 130 8.129 LEN_TRIM — Length of a character entity without trailing blank characters.................................................... 130 8.130 LGE — Lexical greater than or equal....................... 130 8.131 LGT — Lexical greater than................................ 131 8.132 LINK — Create a hard link................................. 132 8.133 LLE — Lexical less than or equal........................... 132 8.134 LLT — Lexical less than.................................... 133 8.135 LNBLNK — Index of the last non-blank character in a string.. 133 8.136 LOC — Returns the address of a variable................... 134 8.137 LOG — Logarithm function................................. 134 8.138 LOG10 — Base 10 logarithm function....................... 135 8.139 LOG_GAMMA — Logarithm of the Gamma function........... 135 8.140 LOGICAL — Convert to logical type......................... 136 8.141 LONG — Convert to integer type............................ 136 8.142 LSHIFT — Left shift bits................................... 137 8.143 LSTAT — Get file status.................................... 137 8.144 LTIME — Convert time to local time info................... 138 8.145 MALLOC — Allocate dynamic memory...................... 138 8.146 MATMUL — matrix multiplication........................... 139 8.147 MAX — Maximum value of an argument list................. 140 8.148 MAXEXPONENT — Maximum exponent of a real kind......... 140 8.149 MAXLOC — Location of the maximum value within an array.. 141 8.150 MAXVAL — Maximum value of an array..................... 141 8.151 MCLOCK — Time function.................................. 142 8.152 MCLOCK8 — Time function (64-bit)......................... 142 8.153 MERGE — Merge variables.................................. 143 8.154 MIN — Minimum value of an argument list................. 143 8.155 MINEXPONENT — Minimum exponent of a real kind......... 144 8.156 MINLOC — Location of the minimum value within an array.. 144 8.157 MINVAL — Minimum value of an array..................... 145 8.158 MOD — Remainder function................................ 146 8.159 MODULO — Modulo function................................ 146 8.160 MOVE_ALLOC — Move allocation from one object to another.............................................................. 147 8.161 MVBITS — Move bits from one integer to another........... 148 8.162 NEAREST — Nearest representable number.................. 148 8.163 NEW_LINE — New line character............................ 149 8.164 NINT — Nearest whole number............................. 149 8.165 NOT — Logical negation.................................... 150 ix 8.166 NULL — Function that returns an disassociated pointer..... 150 8.167 OR — Bitwise logical OR................................... 151 8.168 PACK — Pack an array into an array of rank one............ 151 8.169 PERROR — Print system error message...................... 152 8.170 PRECISION — Decimal precision of a real kind.............. 152 8.171 PRESENT — Determine whether an optional dummy argument is specified...................................................... 153 8.172 PRODUCT — Product of array elements...................... 153 8.173 RADIX — Base of a model number.......................... 154 8.174 RAN — Real pseudo-random number........................ 155 8.175 RAND — Real pseudo-random number...................... 155 8.176 RANDOM_NUMBER — Pseudo-random number................. 155 8.177 RANDOM_SEED — Initialize a pseudo-random number sequence.............................................................. 156 8.178 RANGE — Decimal exponent range.......................... 157 8.179 REAL — Convert to real type............................... 157 8.180 RENAME — Rename a file................................... 158 8.181 REPEAT — Repeated string concatenation.................. 159 8.182 RESHAPE — Function to reshape an array................... 159 8.183 RRSPACING — Reciprocal of the relative spacing............ 160 8.184 RSHIFT — Right shift bits................................. 160 8.185 SCALE — Scale a real value................................ 160 8.186 SCAN — Scan a string for the presence of a set of characters.............................................................. 161 8.187 SECNDS — Time function.................................. 162 8.188 SECOND — CPU time function.............................. 162 8.189 SELECTED_CHAR_KIND — Choose character kind............ 163 8.190 SELECTED_INT_KIND — Choose integer kind................ 163 8.191 SELECTED_REAL_KIND — Choose real kind.................. 164 8.192 SET_EXPONENT — Set the exponent of the model........... 164 8.193 SHAPE — Determine the shape of an array.................. 165 8.194 SIGN — Sign copying function............................. 165 8.195 SIGNAL — Signal handling subroutine (or function)......... 166 8.196 SIN — Sine function....................................... 167 8.197 SINH — Hyperbolic sine function........................... 167 8.198 SIZE — Determine the size of an array..................... 168 8.199 SIZEOF — Size in bytes of an expression................... 168 8.200 SLEEP — Sleep for the specified number of seconds......... 169 8.201 SNGL — Convert double precision real to default real....... 169 8.202 SPACING — Smallest distance between two numbers of a given type.......................................................... 170 8.203 SPREAD — Add a dimension to an array.................... 170 8.204 SQRT — Square-root function.............................. 171 8.205 SRAND — Reinitialize the random number generator........ 171 8.206 STAT — Get file status..................................... 172 8.207 SUM — Sum of array elements.............................. 173 8.208 SYMLNK — Create a symbolic link.......................... 174 8.209 SYSTEM — Execute a shell command....................... 174 x The GNU Fortran Compiler 8.210 SYSTEM_CLOCK — Time function........................... 175 8.211 TAN — Tangent function................................... 175 8.212 TANH — Hyperbolic tangent function....................... 176 8.213 TIME — Time function..................................... 176 8.214 TIME8 — Time function (64-bit)........................... 177 8.215 TINY — Smallest positive number of a real kind............ 177 8.216 TRAILZ — Number of trailing zero bits of an integer........ 178 8.217 TRANSFER — Transfer bit patterns......................... 178 8.218 TRANSPOSE — Transpose an array of rank two.............. 179 8.219 TRIM — Remove trailing blank characters of a string....... 179 8.220 TTYNAM — Get the name of a terminal device............... 180 8.221 UBOUND — Upper dimension bounds of an array............ 180 8.222 UMASK — Set the file creation mask........................ 181 8.223 UNLINK — Remove a file from the file system............... 181 8.224 UNPACK — Unpack an array of rank one into an array...... 182 8.225 VERIFY — Scan a string for the absence of a set of characters.............................................................. 182 8.226 XOR — Bitwise logical exclusive OR........................ 183 9 Intrinsic Modules............................ 185 9.1 ISO_FORTRAN_ENV............................................ 185 9.2 ISO_C_BINDING.............................................. 185 9.3 OpenMP Modules OMP_LIB and OMP_LIB_KINDS.............. 187 Contributing..................................... 189 Contributors to GNU Fortran..................................... 189 Projects.......................................................... 190 Proposed Extensions.............................................. 190 Compiler extensions:........................................... 190 Environment Options.......................................... 191 GNU General Public License................... 193 GNU Free Documentation License............. 205 ADDENDUM: How to use this License for your documents........ 211 Funding Free Software........................... 213 Option Index..................................... 215 Keyword Index................................... 217 Chapter 1: Introduction 1 1 Introduction This manual documents the use of gfortran, the GNU Fortran compiler. You can find in this manual how to invoke gfortran, as well as its features and incompatibilities. The GNU Fortran compiler front end was designed initially as a free replacement for, or alternative to, the unix f95 command; gfortran is the command you’ll use to invoke the compiler. 1.1 About GNU Fortran The GNU Fortran compiler supports the Fortran 77, 90 and 95 standards completely, parts of the Fortran 2003 and Fortran 2008 standards, and several vendor extensions. The devel- opment goal is to provide the following features: Read a user’s program, stored in a file and containing instructions written in Fortran 77, Fortran 90, Fortran 95, Fortran 2003 or Fortran 2008. This file contains source code. Translate the user’s program into instructions a computer can carry out more quickly than it takes to translate the instructions in the first place. The result after compilation of a program is machine code, code designed to be efficiently translated and processed by a machine such as your computer. Humans usually aren’t as good writing machine code as they are at writing Fortran (or C++, Ada, or Java), because it is easy to make tiny mistakes writing machine code. Provide the user with information about the reasons why the compiler is unable to create a binary from the source code. Usually this will be the case if the source code is flawed. The Fortran 90 standard requires that the compiler can point out mistakes to the user. An incorrect usage of the language causes an error message. The compiler will also attempt to diagnose cases where the user’s program contains a correct usage of the language, but instructs the computer to do something questionable. This kind of diagnostics message is called a warning message. Provide optional information about the translation passes from the source code to machine code. This can help a user of the compiler to find the cause of certain bugs which may not be obvious in the source code, but may be more easily found at a lower level compiler output. It also helps developers to find bugs in the compiler itself. Provide information in the generated machine code that can make it easier to find bugs in the program (using a debugging tool, called a debugger, such as the GNU Debugger gdb). Locate and gather machine code already generated to perform actions requested by statements in the user’s program. This machine code is organized into modules and is located and linked to the user program. The GNU Fortran compiler consists of several components: A version of the gcc command (which also might be installed as the system’s cc com- mand) that also understands and accepts Fortran source code. The gcc command is the driver program for all the languages in the GNU Compiler Collection (GCC); With gcc, you can compile the source code of any language for which a front end is available in GCC. 2 The GNU Fortran Compiler The gfortran command itself, which also might be installed as the system’s f95 com- mand. gfortran is just another driver program, but specifically for the Fortran com- piler only. The difference with gcc is that gfortran will automatically link the correct libraries to your program. A collection of run-time libraries. These libraries contain the machine code needed to support capabilities of the Fortran language that are not directly provided by the machine code generated by the gfortran compilation phase, such as intrinsic functions and subroutines, and routines for interaction with files and the operating system. The Fortran compiler itself, (f951). This is the GNU Fortran parser and code generator, linked to and interfaced with the GCC backend library. f951 “translates” the source code to assembler code. You would typically not use this program directly; instead, the gcc or gfortran driver programs will call it for you. 1.2 GNU Fortran and GCC GNU Fortran is a part of GCC, the GNU Compiler Collection. GCC consists of a collec- tion of front ends for various languages, which translate the source code into a language- independent form called GENERIC. This is then processed by a common middle end which provides optimization, and then passed to one of a collection of back ends which generate code for different computer architectures and operating systems. Functionally, this is implemented with a driver program (gcc) which provides the command-line interface for the compiler. It calls the relevant compiler front-end program (e.g., f951 for Fortran) for each file in the source code, and then calls the assembler and linker as appropriate to produce the compiled output. In a copy of GCC which has been compiled with Fortran language support enabled, gcc will recognize files with ‘.f’, ‘.for’, ‘.ftn’, ‘.f90’, ‘.f95’, ‘.f03’ and ‘.f08’ extensions as Fortran source code, and compile it accordingly. A gfortran driver program is also provided, which is identical to gcc except that it automatically links the Fortran runtime libraries into the compiled program. Source files with ‘.f’, ‘.for’, ‘.fpp’, ‘.ftn’, ‘.F’, ‘.FOR’, ‘.FPP’, and ‘.FTN’ extensions are treated as fixed form. Source files with ‘.f90’, ‘.f95’, ‘.f03’, ‘.f08’, ‘.F90’, ‘.F95’, ‘.F03’ and ‘.F08’ extensions are treated as free form. The capitalized versions of either form are run through preprocessing. Source files with the lower case ‘.fpp’ extension are also run through preprocessing. This manual specifically documents the Fortran front end, which handles the program- ming language’s syntax and semantics. The aspects of GCC which relate to the optimization passes and the back-end code generation are documented in the GCC manual; see Section “Introduction” in Using the GNU Compiler Collection (GCC). The two manuals together provide a complete reference for the GNU Fortran compiler. 1.3 Preprocessing and conditional compilation Many Fortran compilers including GNU Fortran allow passing the source code through a C preprocessor (CPP; sometimes also called the Fortran preprocessor, FPP) to allow for conditional compilation. In the case of GNU Fortran, this is the GNU C Preprocessor in the traditional mode. On systems with case-preserving file names, the preprocessor is automatically invoked if the filename extension is.F,.FOR,.FTN,.fpp,.FPP,.F90,.F95, Chapter 1: Introduction 3.F03 or.F08. To manually invoke the preprocessor on any file, use ‘-cpp’, to disable preprocessing on files where the preprocessor is run automatically, use ‘-nocpp’. If a preprocessed file includes another file with the Fortran INCLUDE statement, the in- cluded file is not preprocessed. To preprocess included files, use the equivalent preprocessor statement #include. If GNU Fortran invokes the preprocessor, __GFORTRAN__ is defined and __GNUC__, _ _GNUC_MINOR__ and __GNUC_PATCHLEVEL__ can be used to determine the version of the compiler. See Section “Overview” in The C Preprocessor for details. While CPP is the de-facto standard for preprocessing Fortran code, Part 3 of the Fortran 95 standard (ISO/IEC 1539-3:1998) defines Conditional Compilation, which is not widely used and not directly supported by the GNU Fortran compiler. You can use the program coco to preprocess such files (http://users.erols.com/dnagle/coco.html). 1.4 GNU Fortran and G77 The GNU Fortran compiler is the successor to g77, the Fortran 77 front end included in GCC prior to version 4. It is an entirely new program that has been designed to provide Fortran 95 support and extensibility for future Fortran language standards, as well as providing backwards compatibility for Fortran 77 and nearly all of the GNU language extensions supported by g77. 1.5 Project Status As soon as gfortran can parse all of the statements correctly, it will be in the “larva” state. When we generate code, the “puppa” state. When gfortran is done, we’ll see if it will be a beautiful butterfly, or just a big bug.... –Andy Vaught, April 2000 The start of the GNU Fortran 95 project was announced on the GCC homepage in March 18, 2000 (even though Andy had already been working on it for a while, of course). The GNU Fortran compiler is able to compile nearly all standard-compliant Fortran 95, Fortran 90, and Fortran 77 programs, including a number of standard and non-standard extensions, and can be used on real-world programs. In particular, the supported extensions include OpenMP, Cray-style pointers, and several Fortran 2003 and Fortran 2008 features such as enumeration, stream I/O, and some of the enhancements to allocatable array support from TR 15581. However, it is still under development and has a few remaining rough edges. At present, the GNU Fortran compiler passes the NIST Fortran 77 Test Suite, and produces acceptable results on the LAPACK Test Suite. It also provides respectable per- formance on the Polyhedron Fortran compiler benchmarks and the Livermore Fortran Ker- nels test. It has been used to compile a number of large real-world programs, including the HIRLAM weather-forecasting code and the Tonto quantum chemistry package; see http://gcc.gnu.org/wiki/GfortranApps for an extended list. Among other things, the GNU Fortran compiler is intended as a replacement for G77. At this point, nearly all programs that could be compiled with G77 can be compiled with GNU Fortran, although there are a few minor known regressions. The primary work remaining to be done on GNU Fortran falls into three categories: bug fixing (primarily regarding the treatment of invalid code and providing useful error 4 The GNU Fortran Compiler messages), improving the compiler optimizations and the performance of compiled code, and extending the compiler to support future standards—in particular, Fortran 2003 and Fortran 2008. 1.6 Standards The GNU Fortran compiler implements ISO/IEC 1539:1997 (Fortran 95). As such, it can also compile essentially all standard-compliant Fortran 90 and Fortran 77 programs. It also supports the ISO/IEC TR-15581 enhancements to allocatable arrays, and the OpenMP Application Program Interface v2.5 specification. In the future, the GNU Fortran compiler will also support ISO/IEC 1539-1:2004 (Fortran 2003) and future Fortran standards. Partial support of that standard is already provided; the current status of Fortran 2003 support is reported in the Section 4.1 [Fortran 2003 status], page 31 section of the documentation. The next version of the Fortran standard (Fortran 2008) is currently being developed and the GNU Fortran compiler supports some of its new features. This support is based on the latest draft of the standard (available from http://www.nag.co.uk/sc22wg5/) and no guarantee of future compatibility is made, as the final standard might differ from the draft. For more information, see the Section 4.2 [Fortran 2008 status], page 32 section. Additionally, the GNU Fortran compilers supports the OpenMP specification (version 3.0, http://openmp.org/wp/openmp-specifications/). 1.6.1 Varying Length Character Strings The Fortran 95 standard specifies in Part 2 (ISO/IEC 1539-2:2000) varying length character strings. While GNU Fortran currently does not support such strings directly, there exist two Fortran implementations for them, which work with GNU Fortran. They can be found at http://www.fortran.com/iso_varying_string.f95 and at ftp://ftp.nag.co.uk/ sc22wg5/ISO_VARYING_STRING/. Chapter 1: Introduction 5 Part I: Invoking GNU Fortran Chapter 2: GNU Fortran Command Options 7 2 GNU Fortran Command Options The gfortran command supports all the options supported by the gcc command. Only options specific to GNU Fortran are documented here. See Section “GCC Command Options” in Using the GNU Compiler Collection (GCC), for information on the non-Fortran-specific aspects of the gcc command (and, therefore, the gfortran command). All GCC and GNU Fortran options are accepted both by gfortran and by gcc (as well as any other drivers built at the same time, such as g++), since adding GNU Fortran to the GCC distribution enables acceptance of GNU Fortran options by all of the relevant drivers. In some cases, options have positive and negative forms; the negative form of ‘-ffoo’ would be ‘-fno-foo’. This manual documents only one of these two forms, whichever one is not the default. 2.1 Option summary Here is a summary of all the options specific to GNU Fortran, grouped by type. Explanations are in the following sections. Fortran Language Options See Section 2.2 [Options controlling Fortran dialect], page 8. -fall-intrinsics -ffree-form -fno-fixed-form -fdollar-ok -fimplicit-none -fmax-identifier-length -std=std -fd-lines-as-code -fd-lines-as-comments -ffixed-line-length-n -ffixed-line-length-none -ffree-line-length-n -ffree-line-length-none -fdefault-double-8 -fdefault-integer-8 -fdefault-real-8 -fcray-pointer -fopenmp -fno-range-check -fbackslash -fmodule-private Preprocessing Options See Section 2.3 [Enable and customize preprocessing], page 10. -cpp -dD -dI -dM -dN -dU -fworking-directory -imultilib dir -iprefix file -isysroot dir -iquote -isystem dir -nocpp -nostdinc -undef -Aquestion =answer -A-question [=answer ] -C -CC -Dmacro [=defn ] -Umacro -H -P Error and Warning Options See Section 2.4 [Options to request or suppress errors and warnings], page 13. -fmax-errors=n -fsyntax-only -pedantic -pedantic-errors -Wall -Waliasing -Wampersand -Warray-bounds -Wcharacter-truncation -Wconversion -Wimplicit-interface -Wimplicit-procedure -Wline-truncation -Wintrinsics-std -Wsurprising -Wno-tabs -Wunderflow -Wunused-parameter -Wintrinsics-shadow -Wno-align-commons Debugging Options See Section 2.5 [Options for debugging your program or GNU Fortran], page 16. -fdump-parse-tree -ffpe-trap=list -fdump-core -fbacktrace Directory Options See Section 2.6 [Options for directory search], page 17. 8 The GNU Fortran Compiler -Idir -Jdir -fintrinsic-modules-path dir Link Options See Section 2.7 [Options for influencing the linking step], page 17. -static-libgfortran Runtime Options See Section 2.8 [Options for influencing runtime behavior], page 17. -fconvert=conversion -fno-range-check -frecord-marker=length -fmax-subrecord-length=length -fsign-zero Code Generation Options See Section 2.9 [Options for code generation conventions], page 18. -fno-automatic -ff2c -fno-underscoring -fwhole-file -fsecond-underscore -fbounds-check -fcheck-array-temporaries -fmax-array-constructor =n -fcheck= -fmax-stack-var- size=n -fpack-derived -frepack-arrays -fshort-enums -fexternal-blas -fblas-matmul-limit=n -frecursive -finit-local-zero -finit-integer=n -finit-real= -finit-logical= -finit-character=n -fno-align-commons -fno-protect-parens 2.2 Options controlling Fortran dialect The following options control the details of the Fortran dialect accepted by the compiler: -ffree-form -ffixed-form Specify the layout used by the source file. The free form layout was introduced in Fortran 90. Fixed form was traditionally used in older Fortran programs. When neither option is specified, the source form is determined by the file extension. -fall-intrinsics This option causes all intrinsic procedures (including the GNU-specific exten- sions) to be accepted. This can be useful with ‘-std=f95’ to force standard- compliance but get access to the full range of intrinsics available with gfortran. As a consequence, ‘-Wintrinsics-std’ will be ignored and no user-defined pro- cedure with the same name as any intrinsic will be called except when it is explicitly declared EXTERNAL. -fd-lines-as-code -fd-lines-as-comments Enable special treatment for lines beginning with d or D in fixed form sources. If the ‘-fd-lines-as-code’ option is given they are treated as if the first column contained a blank. If the ‘-fd-lines-as-comments’ option is given, they are treated as comment lines. -fdefault-double-8 Set the DOUBLE PRECISION type to an 8 byte wide type. If ‘-fdefault-real-8’ is given, DOUBLE PRECISION would instead be promoted to 16 bytes if possible, Chapter 2: GNU Fortran Command Options 9 and ‘-fdefault-double-8’ can be used to prevent this. The kind of real con- stants like 1.d0 will not be changed by ‘-fdefault-real-8’ though, so also ‘-fdefault-double-8’ does not affect it. -fdefault-integer-8 Set the default integer and logical types to an 8 byte wide type. Do nothing if this is already the default. This option also affects the kind of integer constants like 42. -fdefault-real-8 Set the default real type to an 8 byte wide type. Do nothing if this is already the default. This option also affects the kind of non-double real constants like 1.0, and does promote the default width of DOUBLE PRECISION to 16 bytes if possible, unless -fdefault-double-8 is given, too. -fdollar-ok Allow ‘$’ as a valid non-first character in a symbol name. Symbols that start with ‘$’ are rejected since it is unclear which rules to apply to implicit typing as different vendors implement different rules. Using ‘$’ in IMPLICIT statements is also rejected. -fbackslash Change the interpretation of backslashes in string literals from a single back- slash character to “C-style” escape characters. The following combinations are expanded \a, \b, \f, \n, \r, \t, \v, \\, and \0 to the ASCII characters alert, backspace, form feed, newline, carriage return, horizontal tab, vertical tab, backslash, and NUL, respectively. Additionally, \xnn, \unnnn and \Unnnnnnnn (where each n is a hexadecimal digit) are translated into the Unicode charac- ters corresponding to the specified code points. All other combinations of a character preceded by \ are unexpanded. -fmodule-private Set the default accessibility of module entities to PRIVATE. Use-associated en- tities will not be accessible unless they are explicitly declared as PUBLIC. -ffixed-line-length-n Set column after which characters are ignored in typical fixed-form lines in the source file, and through which spaces are assumed (as if padded to that length) after the ends of short fixed-form lines. Popular values for n include 72 (the standard and the default), 80 (card im- age), and 132 (corresponding to “extended-source” options in some popular compilers). n may also be ‘none’, meaning that the entire line is meaningful and that continued character constants never have implicit spaces appended to them to fill out the line. ‘-ffixed-line-length-0’ means the same thing as ‘-ffixed-line-length-none’. -ffree-line-length-n Set column after which characters are ignored in typical free-form lines in the source file. The default value is 132. n may be ‘none’, meaning that the entire line is meaningful. ‘-ffree-line-length-0’ means the same thing as ‘-ffree-line-length-none’. 10 The GNU Fortran Compiler -fmax-identifier-length=n Specify the maximum allowed identifier length. Typical values are 31 (Fortran 95) and 63 (Fortran 2003 and Fortran 2008). -fimplicit-none Specify that no implicit typing is allowed, unless overridden by explicit IMPLICIT statements. This is the equivalent of adding implicit none to the start of every procedure. -fcray-pointer Enable the Cray pointer extension, which provides C-like pointer functionality. -fopenmp Enable the OpenMP extensions. This includes OpenMP !$omp directives in free form and c$omp, *$omp and !$omp directives in fixed form, !$ conditional compilation sentinels in free form and c$, *$ and !$ sentinels in fixed form, and when linking arranges for the OpenMP runtime library to be linked in. The option ‘-fopenmp’ implies ‘-frecursive’. -fno-range-check Disable range checking on results of simplification of constant expressions during compilation. For example, GNU Fortran will give an error at compile time when simplifying a = 1. / 0. With this option, no error will be given and a will be assigned the value +Infinity. If an expression evaluates to a value outside of the relevant range of [-HUGE():HUGE()], then the expression will be replaced by -Inf or +Inf as appropriate. Similarly, DATA i/Z’FFFFFFFF’/ will result in an integer overflow on most systems, but with ‘-fno-range-check’ the value will “wrap around” and i will be initialized to −1 instead. -std=std Specify the standard to which the program is expected to conform, which may be one of ‘f95’, ‘f2003’, ‘f2008’, ‘gnu’, or ‘legacy’. The default value for std is ‘gnu’, which specifies a superset of the Fortran 95 standard that includes all of the extensions supported by GNU Fortran, although warnings will be given for obsolete extensions not recommended for use in new code. The ‘legacy’ value is equivalent but without the warnings for obsolete extensions, and may be useful for old non-standard programs. The ‘f95’, ‘f2003’ and ‘f2008’ values specify strict conformance to the Fortran 95, Fortran 2003 and Fortran 2008 standards, respectively; errors are given for all extensions beyond the relevant language standard, and warnings are given for the Fortran 77 features that are permitted but obsolescent in later standards. 2.3 Enable and customize preprocessing Preprocessor related options. See section Section 1.3 [Preprocessing and conditional com- pilation], page 2 for more detailed information on preprocessing in gfortran. -cpp -nocpp Enable preprocessing. The preprocessor is automatically invoked if the file extension is ‘.fpp’, ‘.FPP’, ‘.F’, ‘.FOR’, ‘.FTN’, ‘.F90’, ‘.F95’, ‘.F03’ or ‘.F08’. Use this option to manually enable preprocessing of any kind of Fortran file. To disable preprocessing of files with any of the above listed extensions, use the negative form: ‘-nocpp’. Chapter 2: GNU Fortran Command Options 11 The preprocessor is run in traditional mode, be aware that any restrictions of the file-format, e.g. fixed-form line width, apply for preprocessed output as well. -dM Instead of the normal output, generate a list of ’#define’ directives for all the macros defined during the execution of the preprocessor, including predefined macros. This gives you a way of finding out what is predefined in your version of the preprocessor. Assuming you have no file ‘foo.f90’, the command touch foo.f90; gfortran -cpp -dM foo.f90 will show all the predefined macros. -dD Like ‘-dM’ except in two respects: it does not include the predefined macros, and it outputs both the #define directives and the result of preprocessing. Both kinds of output go to the standard output file. -dN Like ‘-dD’, but emit only the macro names, not their expansions. -dU Like ‘dD’ except that only macros that are expanded, or whose definedness is tested in preprocessor directives, are output; the output is delayed until the use or test of the macro; and ’#undef’ directives are also output for macros tested but undefined at the time. -dI Output ’#include’ directives in addition to the result of preprocessing. -fworking-directory Enable generation of linemarkers in the preprocessor output that will let the compiler know the current working directory at the time of preprocessing. When this option is enabled, the preprocessor will emit, after the initial line- marker, a second linemarker with the current working directory followed by two slashes. GCC will use this directory, when it’s present in the prepro- cessed input, as the directory emitted as the current working directory in some debugging information formats. This option is implicitly enabled if debug- ging information is enabled, but this can be inhibited with the negated form ‘-fno-working-directory’. If the ‘-P’ flag is present in the command line, this option has no effect, since no #line directives are emitted whatsoever. -idirafter dir Search dir for include files, but do it after all directories specified with ‘-I’ and the standard system directories have been exhausted. dir is treated as a system include directory. If dir begins with =, then the = will be replaced by the sysroot prefix; see ‘--sysroot’ and ‘-isysroot’. -imultilib dir Use dir as a subdirectory of the directory containing target-specific C++ headers. -iprefix prefix Specify prefix as the prefix for subsequent ‘-iwithprefix’ options. If the prefix represents a directory, you should include the final ’/’. -isysroot dir This option is like the ‘--sysroot’ option, but applies only to header files. See the ‘--sysroot’ option for more information. 12 The GNU Fortran Compiler -iquote dir Search dir only for header files requested with #include "file"; they are not searched for #include , before all directories specified by ‘-I’ and before the standard system directories. If dir begins with =, then the = will be replaced by the sysroot prefix; see ‘--sysroot’ and ‘-isysroot’. -isystem dir Search dir for header files, after all directories specified by ‘-I’ but before the standard system directories. Mark it as a system directory, so that it gets the same special treatment as is applied to the standard system directories. If dir begins with =, then the = will be replaced by the sysroot prefix; see ‘--sysroot’ and ‘-isysroot’. -nostdinc Do not search the standard system directories for header files. Only the direc- tories you have specified with ‘-I’ options (and the directory of the current file, if appropriate) are searched. -undef Do not predefine any system-specific or GCC-specific macros. The standard predefined macros remain defined. -Apredicate =answer Make an assertion with the predicate predicate and answer answer. This form is preferred to the older form -A predicate(answer), which is still supported, because it does not use shell special characters. -A-predicate =answer Cancel an assertion with the predicate predicate and answer answer. -C Do not discard comments. All comments are passed through to the output file, except for comments in processed directives, which are deleted along with the directive. You should be prepared for side effects when using ‘-C’; it causes the prepro- cessor to treat comments as tokens in their own right. For example, comments appearing at the start of what would be a directive line have the effect of turn- ing that line into an ordinary source line, since the first token on the line is no longer a ’#’. Warning: this currently handles C-Style comments only. The preprocessor does not yet recognize Fortran-style comments. -CC Do not discard comments, including during macro expansion. This is like ‘-C’, except that comments contained within macros are also passed through to the output file where the macro is expanded. In addition to the side-effects of the ‘-C’ option, the ‘-CC’ option causes all C++-style comments inside a macro to be converted to C-style comments. This is to prevent later use of that macro from inadvertently commenting out the remainder of the source line. The ‘-CC’ option is generally used to support lint comments. Warning: this currently handles C- and C++-Style comments only. The prepro- cessor does not yet recognize Fortran-style comments. Chapter 2: GNU Fortran Command Options 13 -Dname Predefine name as a macro, with definition 1. -Dname =definition The contents of definition are tokenized and processed as if they appeared during translation phase three in a ’#define’ directive. In particular, the definition will be truncated by embedded newline characters. If you are invoking the preprocessor from a shell or shell-like program you may need to use the shell’s quoting syntax to protect characters such as spaces that have a meaning in the shell syntax. If you wish to define a function-like macro on the command line, write its argument list with surrounding parentheses before the equals sign (if any). Parentheses are meaningful to most shells, so you will need to quote the option. With sh and csh, -D’name(args...)=definition’ works. ‘-D’ and ‘-U’ options are processed in the order they are given on the command line. All -imacros file and -include file options are processed after all -D and -U options. -H Print the name of each header file used, in addition to other normal activities. Each name is indented to show how deep in the ’#include’ stack it is. -P Inhibit generation of linemarkers in the output from the preprocessor. This might be useful when running the preprocessor on something that is not C code, and will be sent to a program which might be confused by the linemarkers. -Uname Cancel any previous definition of name, either built in or provided with a ‘-D’ option. 2.4 Options to request or suppress errors and warnings Errors are diagnostic messages that report that the GNU Fortran compiler cannot compile the relevant piece of source code. The compiler will continue to process the program in an attempt to report further errors to aid in debugging, but will not produce any compiled output. Warnings are diagnostic messages that report constructions which are not inherently erroneous but which are risky or suggest there is likely to be a bug in the program. Unless ‘-Werror’ is specified, they do not prevent compilation of the program. You can request many specific warnings with options beginning ‘-W’, for example ‘-Wimplicit’ to request warnings on implicit declarations. Each of these specific warning options also has a negative form beginning ‘-Wno-’ to turn off warnings; for example, ‘-Wno-implicit’. This manual lists only one of the two forms, whichever is not the default. These options control the amount and kinds of errors and warnings produced by GNU Fortran: -fmax-errors=n Limits the maximum number of error messages to n, at which point GNU Fortran bails out rather than attempting to continue processing the source code. If n is 0, there is no limit on the number of error messages produced. 14 The GNU Fortran Compiler -fsyntax-only Check the code for syntax errors, but don’t actually compile it. This will generate module files for each module present in the code, but no other output file. -pedantic Issue warnings for uses of extensions to Fortran 95. ‘-pedantic’ also applies to C-language constructs where they occur in GNU Fortran source files, such as use of ‘\e’ in a character constant within a directive like #include. Valid Fortran 95 programs should compile properly with or without this option. However, without this option, certain GNU extensions and traditional Fortran features are supported as well. With this option, many of them are rejected. Some users try to use ‘-pedantic’ to check programs for conformance. They soon find that it does not do quite what they want—it finds some nonstandard practices, but not all. However, improvements to GNU Fortran in this area are welcome. This should be used in conjunction with ‘-std=f95’, ‘-std=f2003’ or ‘-std=f2008’. -pedantic-errors Like ‘-pedantic’, except that errors are produced rather than warnings. -Wall Enables commonly used warning options pertaining to usage that we recommend avoiding and that we believe are easy to avoid. This currently includes ‘-Waliasing’, ‘-Wampersand’, ‘-Wsurprising’, ‘-Wintrinsics-std’, ‘-Wno-tabs’, ‘-Wintrinsic-shadow’ and ‘-Wline-truncation’. -Waliasing Warn about possible aliasing of dummy arguments. Specifically, it warns if the same actual argument is associated with a dummy argument with INTENT(IN) and a dummy argument with INTENT(OUT) in a call with an explicit interface. The following example will trigger the warning. interface subroutine bar(a,b) integer, intent(in) :: a integer, intent(out) :: b end subroutine end interface integer :: a call bar(a,a) -Wampersand Warn about missing ampersand in continued character constants. The warning is given with ‘-Wampersand’, ‘-pedantic’, ‘-std=f95’, ‘-std=f2003’ and ‘-std=f2008’. Note: With no ampersand given in a continued character constant, GNU Fortran assumes continuation at the first non-comment, non-whitespace character after the ampersand that initiated the continuation. Chapter 2: GNU Fortran Command Options 15 -Warray-temporaries Warn about array temporaries generated by the compiler. The information generated by this warning is sometimes useful in optimization, in order to avoid such temporaries. -Wcharacter-truncation Warn when a character assignment will truncate the assigned string. -Wline-truncation Warn when a source code line will be truncated. -Wconversion Warn about implicit conversions between different types. -Wimplicit-interface Warn if a procedure is called without an explicit interface. Note this only checks that an explicit interface is present. It does not check that the declared interfaces are consistent across program units. -Wimplicit-procedure Warn if a procedure is called that has neither an explicit interface nor has been declared as EXTERNAL. -Wintrinsics-std Warn if gfortran finds a procedure named like an intrinsic not available in the currently selected standard (with ‘-std’) and treats it as EXTERNAL procedure because of this. ‘-fall-intrinsics’ can be used to never trigger this behavior and always link to the intrinsic regardless of the selected standard. -Wsurprising Produce a warning when “suspicious” code constructs are encountered. While technically legal these usually indicate that an error has been made. This currently produces a warning under the following circumstances: An INTEGER SELECT construct has a CASE that can never be matched as its lower value is greater than its upper value. A LOGICAL SELECT construct has three CASE statements. A TRANSFER specifies a source that is shorter than the destination. The type of a function result is declared more than once with the same type. If ‘-pedantic’ or standard-conforming mode is enabled, this is an error. A CHARACTER variable is declared with negative length. -Wtabs By default, tabs are accepted as whitespace, but tabs are not members of the Fortran Character Set. For continuation lines, a tab followed by a digit be- tween 1 and 9 is supported. ‘-Wno-tabs’ will cause a warning to be issued if a tab is encountered. Note, ‘-Wno-tabs’ is active for ‘-pedantic’, ‘-std=f95’, ‘-std=f2003’, ‘-std=f2008’ and ‘-Wall’. -Wunderflow Produce a warning when numerical constant expressions are encountered, which yield an UNDERFLOW during compilation. 16 The GNU Fortran Compiler -Wintrinsic-shadow Warn if a user-defined procedure or module procedure has the same name as an intrinsic; in this case, an explicit interface or EXTERNAL or INTRINSIC declaration might be needed to get calls later resolved to the desired intrin- sic/procedure. -Wunused-parameter Contrary to gcc’s meaning of ‘-Wunused-parameter’, gfortran’s implementa- tion of this option does not warn about unused dummy arguments, but about unused PARAMETER values. ‘-Wunused-parameter’ is not included in ‘-Wall’ but is implied by ‘-Wall -Wextra’. -Walign-commons By default, gfortran warns about any occasion of variables being padded for proper alignment inside a COMMON block. This warning can be turned off via ‘-Wno-align-commons’. See also ‘-falign-commons’. -Werror Turns all warnings into errors. See Section “Options to Request or Suppress Errors and Warnings” in Using the GNU Compiler Collection (GCC), for information on more options offered by the GBE shared by gfortran, gcc and other GNU compilers. Some of these have no effect when compiling programs written in Fortran. 2.5 Options for debugging your program or GNU Fortran GNU Fortran has various special options that are used for debugging either your program or the GNU Fortran compiler. -fdump-parse-tree Output the internal parse tree before starting code generation. Only really useful for debugging the GNU Fortran compiler itself. -ffpe-trap=list Specify a list of IEEE exceptions when a Floating Point Exception (FPE) should be raised. On most systems, this will result in a SIGFPE signal being sent and the program being interrupted, producing a core file useful for debugging. list is a (possibly empty) comma-separated list of the following IEEE exceptions: ‘invalid’ (invalid floating point operation, such as SQRT(-1.0)), ‘zero’ (divi- sion by zero), ‘overflow’ (overflow in a floating point operation), ‘underflow’ (underflow in a floating point operation), ‘precision’ (loss of precision during operation) and ‘denormal’ (operation produced a denormal value). Some of the routines in the Fortran runtime library, like ‘CPU_TIME’, are likely to trigger floating point exceptions when ffpe-trap=precision is used. For this reason, the use of ffpe-trap=precision is not recommended. -fbacktrace Specify that, when a runtime error is encountered or a deadly signal is emitted (segmentation fault, illegal instruction, bus error or floating-point exception), the Fortran runtime library should output a backtrace of the error. This option only has influence for compilation of the Fortran main program. Chapter 2: GNU Fortran Command Options 17 -fdump-core Request that a core-dump file is written to disk when a runtime error is en- countered on systems that support core dumps. This option is only effective for the compilation of the Fortran main program. See Section “Options for Debugging Your Program or GCC” in Using the GNU Compiler Collection (GCC), for more information on debugging options. 2.6 Options for directory search These options affect how GNU Fortran searches for files specified by the INCLUDE directive and where it searches for previously compiled modules. It also affects the search paths used by cpp when used to preprocess Fortran source. -Idir These affect interpretation of the INCLUDE directive (as well as of the #include directive of the cpp preprocessor). Also note that the general behavior of ‘-I’ and INCLUDE is pretty much the same as of ‘-I’ with #include in the cpp preprocessor, with regard to looking for ‘header.gcc’ files and other such things. This path is also used to search for ‘.mod’ files when previously compiled mod- ules are required by a USE statement. See Section “Options for Directory Search” in Using the GNU Compiler Col- lection (GCC), for information on the ‘-I’ option. -Jdir This option specifies where to put ‘.mod’ files for compiled modules. It is also added to the list of directories to searched by an USE statement. The default is the current directory. -fintrinsic-modules-path dir This option specifies the location of pre-compiled intrinsic modules, if they are not in the default location expected by the compiler. 2.7 Influencing the linking step These options come into play when the compiler links object files into an executable output file. They are meaningless if the compiler is not doing a link step. -static-libgfortran On systems that provide ‘libgfortran’ as a shared and a static library, this option forces the use of the static version. If no shared version of ‘libgfortran’ was built when the compiler was configured, this option has no effect. 2.8 Influencing runtime behavior These options affect the runtime behavior of programs compiled with GNU Fortran. -fconvert=conversion Specify the representation of data for unformatted files. Valid values for conversion are: ‘native’, the default; ‘swap’, swap between big- and little-endian; ‘big-endian’, use big-endian representation for unformatted files; ‘little-endian’, use little-endian representation for unformatted files. 18 The GNU Fortran Compiler This option has an effect only when used in the main program. The CONVERT specifier and the GFORTRAN CONVERT UNIT environment variable over- ride the default specified by ‘-fconvert’. -fno-range-check Disable range checking of input values during integer READ operations. For example, GNU Fortran will give an error if an input value is outside of the rele- vant range of [-HUGE():HUGE()]. In other words, with INTEGER (kind=4) :: i , attempting to read −2147483648 will give an error unless ‘-fno-range-check’ is given. -frecord-marker=length Specify the length of record markers for unformatted files. Valid values for length are 4 and 8. Default is 4. This is different from previous versions of gfortran, which specified a default record marker length of 8 on most systems. If you want to read or write files compatible with earlier versions of gfortran, use ‘-frecord-marker=8’. -fmax-subrecord-length=length Specify the maximum length for a subrecord. The maximum permitted value for length is 2147483639, which is also the default. Only really useful for use by the gfortran testsuite. -fsign-zero When enabled, floating point numbers of value zero with the sign bit set are written as negative number in formatted output and treated as negative in the SIGN intrinsic. fno-sign-zero does not print the negative sign of zero values and regards zero as positive number in the SIGN intrinsic for compatibility with F77. Default behavior is to show the negative sign. 2.9 Options for code generation conventions These machine-independent options control the interface conventions used in code genera- tion. Most of them have both positive and negative forms; the negative form of ‘-ffoo’ would be ‘-fno-foo’. In the table below, only one of the forms is listed—the one which is not the default. You can figure out the other form by either removing ‘no-’ or adding it. -fno-automatic Treat each program unit (except those marked as RECURSIVE) as if the SAVE statement were specified for every local variable and array referenced in it. Does not affect common blocks. (Some Fortran compilers provide this option under the name ‘-static’ or ‘-save’.) The default, which is ‘-fautomatic’, uses the stack for local variables smaller than the value given by ‘-fmax-stack-var-size’. Use the option ‘-frecursive’ to use no static memory. -ff2c Generate code designed to be compatible with code generated by g77 and f2c. The calling conventions used by g77 (originally implemented in f2c) require functions that return type default REAL to actually return the C type double, Chapter 2: GNU Fortran Command Options 19 and functions that return type COMPLEX to return the values via an extra argument in the calling sequence that points to where to store the return value. Under the default GNU calling conventions, such functions simply re- turn their results as they would in GNU C—default REAL functions return the C type float, and COMPLEX functions return the GNU C type complex. Additionally, this option implies the ‘-fsecond-underscore’ option, unless ‘-fno-second-underscore’ is explicitly requested. This does not affect the generation of code that interfaces with the libgfortran library. Caution: It is not a good idea to mix Fortran code compiled with ‘-ff2c’ with code compiled with the default ‘-fno-f2c’ calling conventions as, calling COMPLEX or default REAL functions between program parts which were compiled with different calling conventions will break at execution time. Caution: This will break code which passes intrinsic functions of type default REAL or COMPLEX as actual arguments, as the library implementations use the ‘-fno-f2c’ calling conventions. -fno-underscoring Do not transform names of entities specified in the Fortran source file by ap- pending underscores to them. With ‘-funderscoring’ in effect, GNU Fortran appends one underscore to external names with no underscores. This is done to ensure compatibility with code produced by many UNIX Fortran compilers. Caution: The default behavior of GNU Fortran is incompatible with f2c and g77, please use the ‘-ff2c’ option if you want object files compiled with GNU Fortran to be compatible with object code created with these tools. Use of ‘-fno-underscoring’ is not recommended unless you are experimenting with issues such as integration of GNU Fortran into existing system environ- ments (vis-à-vis existing libraries, tools, and so on). For example, with ‘-funderscoring’, and assuming other defaults like ‘-fcase-lower’ and that j() and max_count() are external functions while my_var and lvar are local variables, a statement like I = J() + MAX_COUNT (MY_VAR, LVAR) is implemented as something akin to: i = j_() + max_count__(&my_var__, &lvar); With ‘-fno-underscoring’, the same statement is implemented as: i = j() + max_count(&my_var, &lvar); Use of ‘-fno-underscoring’ allows direct specification of user-defined names while debugging and when interfacing GNU Fortran code with other languages. Note that just because the names match does not mean that the interface implemented by GNU Fortran for an external name matches the interface im- plemented by some other language for that same name. That is, getting code produced by GNU Fortran to link to code produced by some other compiler using this or any other method can be only a small part of the overall solution— getting the code generated by both compilers to agree on issues other than 20 The GNU Fortran Compiler naming can require significant effort, and, unlike naming disagreements, linkers normally cannot detect disagreements in these other areas. Also, note that with ‘-fno-underscoring’, the lack of appended underscores in- troduces the very real possibility that a user-defined external name will conflict with a name in a system library, which could make finding unresolved-reference bugs quite difficult in some cases—they might occur at program run time, and show up only as buggy behavior at run time. In future versions of GNU Fortran we hope to improve naming and linking issues so that debugging always involves using the names as they appear in the source, even if the names as seen by the linker are mangled to prevent accidental linking between procedures with incompatible interfaces. -fwhole-file By default, GNU Fortran parses, resolves and translates each procedure in a file separately. Using this option modifies this such that the whole file is parsed and placed in a single front-end tree. During resolution, in addition to all the usual checks and fixups, references to external procedures that are in the same file effect resolution of that procedure, if not already done, and a check of the interfaces. The dependences are resolved by changing the order in which the file is translated into the backend tree. Thus, a procedure that is referenced is translated before the reference and the duplication of backend tree declarations eliminated. -fsecond-underscore By default, GNU Fortran appends an underscore to external names. If this option is used GNU Fortran appends two underscores to names with underscores and one underscore to external names with no underscores. GNU Fortran also appends two underscores to internal names with underscores to avoid naming collisions with external names. This option has no effect if ‘-fno-underscoring’ is in effect. It is implied by the ‘-ff2c’ option. Otherwise, with this option, an external name such as MAX_COUNT is imple- mented as a reference to the link-time external symbol max_count__, instead of max_count_. This is required for compatibility with g77 and f2c, and is implied by use of the ‘-ff2c’ option. -fcheck= Enable the generation of run-time checks; the argument shall be a comma- delimited list of the following keywords. ‘all’ Enable all run-time test of ‘-fcheck’. ‘array-temps’ Warns at run time when for passing an actual argument a tempo- rary array had to be generated. The information generated by this warning is sometimes useful in optimization, in order to avoid such temporaries. Note: The warning is only printed once per location. Chapter 2: GNU Fortran Command Options 21 ‘bounds’ Enable generation of run-time checks for array subscripts and against the declared minimum and maximum values. It also checks array indices for assumed and deferred shape arrays against the actual allocated bounds and ensures that all string lengths are equal for character array constructors without an explicit typespec. Some checks require that ‘-fcheck=bounds’ is set for the compila- tion of the main program. Note: In the future this may also include other forms of checking, e.g., checking substring references. ‘do’ Enable generation of run-time checks for invalid modification of loop iteration variables. ‘mem’ Enable generation of run-time checks for memory allocation. Note: This option does not affect explicit allocations using the ALLOCATE statement, which will be always checked. ‘pointer’ Enable generation of run-time checks for pointers and allocatables. ‘recursion’ Enable generation of run-time checks for recursively called sub- routines and functions which are not marked as recursive. See also ‘-frecursive’. Note: This check does not work for OpenMP programs and is disabled if used together with ‘-frecursive’ and ‘-fopenmp’. -fbounds-check Deprecated alias for ‘-fcheck=bounds’. -fcheck-array-temporaries Deprecated alias for ‘-fcheck=array-temps’. -fmax-array-constructor=n This option can be used to increase the upper limit permitted in array con- structors. The code below requires this option to expand the array at compile time. program test implicit none integer j integer, parameter :: n = 100000 integer, parameter :: i(n) = (/ (2*j, j = 1, n) /) print ’(10(I0,1X))’, i end program test Caution: This option can lead to long compile times and excessively large object files. The default value for n is 65535. -fmax-stack-var-size=n This option specifies the size in bytes of the largest array that will be put on the stack; if the size is exceeded static memory is used (except in procedures marked as RECURSIVE). Use the option ‘-frecursive’ to allow for recursive 22 The GNU Fortran Compiler procedures which do not have a RECURSIVE attribute or for parallel programs. Use ‘-fno-automatic’ to never use the stack. This option currently only affects local arrays declared with constant bounds, and may not apply to all character variables. Future versions of GNU Fortran may improve this behavior. The default value for n is 32768. -fpack-derived This option tells GNU Fortran to pack derived type members as closely as possible. Code compiled with this option is likely to be incompatible with code compiled without this option, and may execute slower. -frepack-arrays In some circumstances GNU Fortran may pass assumed shape array sections via a descriptor describing a noncontiguous area of memory. This option adds code to the function prologue to repack the data into a contiguous block at runtime. This should result in faster accesses to the array. However it can introduce significant overhead to the function call, especially when the passed data is noncontiguous. -fshort-enums This option is provided for interoperability with C code that was compiled with the ‘-fshort-enums’ option. It will make GNU Fortran choose the smallest INTEGER kind a given enumerator set will fit in, and give all its enumerators this kind. -fexternal-blas This option will make gfortran generate calls to BLAS functions for some matrix operations like MATMUL, instead of using our own algorithms, if the size of the matrices involved is larger than a given limit (see ‘-fblas-matmul-limit’). This may be profitable if an optimized vendor BLAS library is available. The BLAS library will have to be specified at link time. -fblas-matmul-limit=n Only significant when ‘-fexternal-blas’ is in effect. Matrix multiplication of matrices with size larger than (or equal to) n will be performed by calls to BLAS functions, while others will be handled by gfortran internal algorithms. If the matrices involved are not square, the size comparison is performed using the geometric mean of the dimensions of the argument and result matrices. The default value for n is 30. -frecursive Allow indirect recursion by forcing all local arrays to be allocated on the stack. This flag cannot be used together with ‘-fmax-stack-var-size=’ or ‘-fno-automatic’. Chapter 2: GNU Fortran Command Options 23 -finit-local-zero -finit-integer=n -finit-real= -finit-logical= -finit-character=n The ‘-finit-local-zero’ option instructs the compiler to initialize local INTEGER, REAL, and COMPLEX variables to zero, LOGICAL variables to false, and CHARACTER variables to a string of null bytes. Finer-grained initialization options are provided by the ‘-finit-integer=n ’, ‘-finit-real=’ (which also initializes the real and imaginary parts of local COMPLEX variables), ‘-finit-logical=’, and ‘-finit-character=n ’ (where n is an ASCII character value) options. These options do not initialize components of derived type variables, nor do they initialize variables that appear in an EQUIVALENCE statement. (This limitation may be removed in future releases). Note that the ‘-finit-real=nan’ option initializes REAL and COMPLEX variables with a quiet NaN. For a signalling NaN use ‘-finit-real=snan’; note, however, that compile-time optimizations may convert them into quiet NaN and that trapping needs to be enabled (e.g. via ‘-ffpe-trap’). -falign-commons By default, gfortran enforces proper alignment of all variables in a COM- MON block by padding them as needed. On certain platforms this is manda- tory, on others it increases performance. If a COMMON block is not declared with consistent data types everywhere, this padding can cause trouble, and ‘-fno-align-commons ’ can be used to disable automatic alignment. The same form of this option should be used for all files that share a COMMON block. To avoid potential alignment issues in COMMON blocks, it is recommended to order objects from largests to smallest. -fno-protect-parens By default the parentheses in expression are honored for all optimization levels such that the compiler does not do any re-association. Using ‘-fno-protect-parens’ allows the compiler to reorder REAL and COMPLEX expressions to produce faster code. Note that for the re-association optimization ‘-fno-signed-zeros’ and ‘-fno-trapping-math’ need to be in effect. See Section “Options for Code Generation Conventions” in Using the GNU Compiler Collection (GCC), for information on more options offered by the GBE shared by gfortran, gcc, and other GNU compilers. 2.10 Environment variables affecting gfortran The gfortran compiler currently does not make use of any environment variables to control its operation above and beyond those that affect the operation of gcc. See Section “Environment Variables Affecting GCC” in Using the GNU Compiler Col- lection (GCC), for information on environment variables. 24 The GNU Fortran Compiler See Chapter 3 [Runtime], page 25, for environment variables that affect the run-time behavior of programs compiled with GNU Fortran. Chapter 3: Runtime: Influencing runtime behavior with environment variables 25 3 Runtime: Influencing runtime behavior with environment variables The behavior of the gfortran can be influenced by environment variables. Malformed environment variables are silently ignored. 3.1 GFORTRAN_STDIN_UNIT—Unit number for standard input This environment variable can be used to select the unit number preconnected to standard input. This must be a positive integer. The default value is 5. 3.2 GFORTRAN_STDOUT_UNIT—Unit number for standard output This environment variable can be used to select the unit number preconnected to standard output. This must be a positive integer. The default value is 6. 3.3 GFORTRAN_STDERR_UNIT—Unit number for standard error This environment variable can be used to select the unit number preconnected to standard error. This must be a positive integer. The default value is 0. 3.4 GFORTRAN_USE_STDERR—Send library output to standard error This environment variable controls where library output is sent. If the first letter is ‘y’, ‘Y’ or ‘1’, standard error is used. If the first letter is ‘n’, ‘N’ or ‘0’, standard output is used. 3.5 GFORTRAN_TMPDIR—Directory for scratch files This environment variable controls where scratch files are created. If this environment variable is missing, GNU Fortran searches for the environment variable TMP. If this is also missing, the default is ‘/tmp’. 3.6 GFORTRAN_UNBUFFERED_ALL—Don’t buffer I/O on all units This environment variable controls whether all I/O is unbuffered. If the first letter is ‘y’, ‘Y’ or ‘1’, all I/O is unbuffered. This will slow down small sequential reads and writes. If the first letter is ‘n’, ‘N’ or ‘0’, I/O is buffered. This is the default. 3.7 GFORTRAN_UNBUFFERED_PRECONNECTED—Don’t buffer I/O on preconnected units The environment variable named GFORTRAN_UNBUFFERED_PRECONNECTED controls whether I/O on a preconnected unit (i.e. STDOUT or STDERR) is unbuffered. If the first letter is ‘y’, ‘Y’ or ‘1’, I/O is unbuffered. This will slow down small sequential reads and writes. If the first letter is ‘n’, ‘N’ or ‘0’, I/O is buffered. This is the default. 3.8 GFORTRAN_SHOW_LOCUS—Show location for runtime errors If the first letter is ‘y’, ‘Y’ or ‘1’, filename and line numbers for runtime errors are printed. If the first letter is ‘n’, ‘N’ or ‘0’, don’t print filename and line numbers for runtime errors. The default is to print the location. 26 The GNU Fortran Compiler 3.9 GFORTRAN_OPTIONAL_PLUS—Print leading + where permitted If the first letter is ‘y’, ‘Y’ or ‘1’, a plus sign is printed where permitted by the Fortran standard. If the first letter is ‘n’, ‘N’ or ‘0’, a plus sign is not printed in most cases. Default is not to print plus signs. 3.10 GFORTRAN_DEFAULT_RECL—Default record length for new files This environment variable specifies the default record length, in bytes, for files which are opened without a RECL tag in the OPEN statement. This must be a positive integer. The default value is 1073741824 bytes (1 GB). 3.11 GFORTRAN_LIST_SEPARATOR—Separator for list output This environment variable specifies the separator when writing list-directed output. It may contain any number of spaces and at most one comma. If you specify this on the command line, be sure to quote spaces, as in $ GFORTRAN_LIST_SEPARATOR=’ , ’./a.out when a.out is the compiled Fortran program that you want to run. Default is a single space. 3.12 GFORTRAN_CONVERT_UNIT—Set endianness for unformatted I/O By setting the GFORTRAN_CONVERT_UNIT variable, it is possible to change the representation of data for unformatted files. The syntax for the GFORTRAN_CONVERT_UNIT variable is: GFORTRAN_CONVERT_UNIT: mode | mode ’;’ exception | exception ; mode: ’native’ | ’swap’ | ’big_endian’ | ’little_endian’ ; exception: mode ’:’ unit_list | unit_list ; unit_list: unit_spec | unit_list unit_spec ; unit_spec: INTEGER | INTEGER ’-’ INTEGER ; The variable consists of an optional default mode, followed by a list of optional excep- tions, which are separated by semicolons from the preceding default and each other. Each exception consists of a format and a comma-separated list of units. Valid values for the modes are the same as for the CONVERT specifier: NATIVE Use the native format. This is the default. SWAP Swap between little- and big-endian. LITTLE_ENDIAN Use the little-endian format for unformatted files. BIG_ENDIAN Use the big-endian format for unformatted files. A missing mode for an exception is taken to mean BIG_ENDIAN. Examples of values for GFORTRAN_CONVERT_UNIT are: ’big_endian’ Do all unformatted I/O in big endian mode. ’little_endian;native:10-20,25’ Do all unformatted I/O in little endian mode, except for units 10 to 20 and 25, which are in native format. ’10-20’ Units 10 to 20 are big-endian, the rest is native. Chapter 3: Runtime: Influencing runtime behavior with environment variables 27 Setting the environment variables should be done on the command line or via the export command for sh-compatible shells and via setenv for csh-compatible shells. Example for sh: $ gfortran foo.f90 $ GFORTRAN_CONVERT_UNIT=’big_endian;native:10-20’./a.out Example code for csh: % gfortran foo.f90 % setenv GFORTRAN_CONVERT_UNIT ’big_endian;native:10-20’ %./a.out Using anything but the native representation for unformatted data carries a significant speed overhead. If speed in this area matters to you, it is best if you use this only for data that needs to be portable. See Section 6.1.14 [CONVERT specifier], page 41, for an alternative way to specify the data representation for unformatted files. See Section 2.8 [Runtime Options], page 17, for setting a default data representation for the whole program. The CONVERT specifier overrides the ‘-fconve

Use Quizgecko on...
Browser
Browser