     [file gcc-common.texi not included]

This file documents the use and the internals of the GNU Fortran compiler, (gfortran).

Published by the Free Software Foundation 51 Franklin Street, Fifth Floor Boston, MA 02110-1301 USA

Copyright © 1999-2015 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.3 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.

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.

Introduction
************

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 will use to invoke the compiler.

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 development 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 are not 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 command) 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.

  * The gfortran command itself, which also might be installed as the system's f95 command. gfortran is just another driver program, but specifically for the Fortran compiler 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.

GNU Fortran and GCC
===================

GNU Fortran is a part of GCC, the GNU Compiler Collection.  GCC consists of a collection 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 programming 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 Introduction (Using the GNU Compiler Collection (GCC)). The two manuals together provide a complete reference for the GNU Fortran compiler.

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, .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 included 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 Overview (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://www.daniellnagle.com/coco.html).

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.

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, including TR 15581.  However, it is still under development and has a few remaining rough edges. There also is initial support for OpenACC. Note that this is an experimental feature, incomplete, and subject to change in future versions of GCC.  See https://gcc.gnu.org/wiki/OpenACC for more information.

At present, the GNU Fortran compiler passes the NIST Fortran 77 Test Suite (http://www.fortran-2000.com/ArnaudRecipes/fcvs21_f95.html), and produces acceptable results on the LAPACK Test Suite (http://www.netlib.org/lapack/faq.html#1.21). It also provides respectable performance on the Polyhedron Fortran compiler benchmarks (http://www.polyhedron.com/fortran-compiler-comparisons/polyhedron-benchmark-suite) and the Livermore Fortran Kernels test (http://www.netlib.org/benchmark/livermore).  It has been used to compile a number of large real-world programs, including the HARMONIE and HIRLAM weather forecasting code (http://hirlam.org/) and the Tonto quantum chemistry package (http://physical-chemistry.scb.uwa.edu.au/tonto/wiki/index.php/Main_Page); see https://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 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.

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.

GNU Fortran also have a partial support for ISO/IEC 1539-1:2004 (Fortran 2003), ISO/IEC 1539-1:2010 (Fortran 2008), the Technical Specification Further Interoperability of Fortran with C (ISO/IEC TS 29113:2012). Full support of those standards and future Fortran standards is planned. The current status of the support is can be found in the Fortran 2003 status, Fortran 2008 status and TS 29113 status sections of the documentation.

Additionally, the GNU Fortran compilers supports the OpenMP specification (version 4.0, http://openmp.org/wp/openmp-specifications/). There also is initial support for the OpenACC specification (targeting version 2.0, http://www.openacc.org/). Note that this is an experimental feature, incomplete, and subject to change in future versions of GCC.  See https://gcc.gnu.org/wiki/OpenACC for more information.

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/.

Deferred-length character strings of Fortran 2003 supports part of the features of ISO_VARYING_STRING and should be considered as replacement. (Namely, allocatable or pointers of the type character(len=:).)

     [file invoke.texi not included]

Runtime: Influencing runtime behavior with environment variables
****************************************************************

The behavior of the gfortran can be influenced by environment variables.

Malformed environment variables are silently ignored.

TMPDIR---Directory for scratch files
====================================

When opening a file with STATUS='SCRATCH', GNU Fortran tries to create the file in one of the potential directories by testing each directory in the order below.

 1. The environment variable TMPDIR, if it exists.

 2. On the MinGW target, the directory returned by the GetTempPath function. Alternatively, on the Cygwin target, the TMP and TEMP environment variables, if they exist, in that order.

 3. The P_tmpdir macro if it is defined, otherwise the directory /tmp.

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.

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.

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.

GFORTRAN_UNBUFFERED_ALL---Do not 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.

GFORTRAN_UNBUFFERED_PRECONNECTED---Do not 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.

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, do not print filename and line numbers for runtime errors.  The default is to print the location.

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.

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).

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.

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 exceptions, 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.

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 CONVERT specifier, for an alternative way to specify the data representation for unformatted files.  See Runtime Options, for setting a default data representation for the whole program.  The CONVERT specifier overrides the -fconvert compile options.

Note that the values specified via the GFORTRAN_CONVERT_UNIT environment variable will override the CONVERT specifier in the open statement.  This is to give control over data formats to users who do not have the source code of their program available.

GFORTRAN_ERROR_BACKTRACE---Show backtrace on run-time errors
============================================================

If the GFORTRAN_ERROR_BACKTRACE variable is set to y, Y or 1 (only the first letter is relevant) then a backtrace is printed when a serious run-time error occurs.  To disable the backtracing, set the variable to n, N, 0. Default is to print a backtrace unless the -fno-backtrace compile option was used.

Fortran 2003 and 2008 Status
****************************

Fortran 2003 status
===================

GNU Fortran supports several Fortran 2003 features; an incomplete list can be found below.  See also the wiki page (https://gcc.gnu.org/wiki/Fortran2003) about Fortran 2003.

  * Procedure pointers including procedure-pointer components with PASS attribute.

  * Procedures which are bound to a derived type (type-bound procedures) including PASS, PROCEDURE and GENERIC, and operators bound to a type.

  * Abstract interfaces and type extension with the possibility to override type-bound procedures or to have deferred binding.

  * Polymorphic entities (``CLASS'') for derived types and unlimited polymorphism (``CLASS(*)'') -- including SAME_TYPE_AS, EXTENDS_TYPE_OF and SELECT TYPE for scalars and arrays and finalization.

  * Generic interface names, which have the same name as derived types, are now supported. This allows one to write constructor functions.  Note that Fortran does not support static constructor functions.  For static variables, only default initialization or structure-constructor initialization are available.

  * The ASSOCIATE construct.

  * Interoperability with C including enumerations,

  * In structure constructors the components with default values may be omitted.

  * Extensions to the ALLOCATE statement, allowing for a type-specification with type parameter and for allocation and initialization from a SOURCE= expression; ALLOCATE and DEALLOCATE optionally return an error message string via ERRMSG=.

  * Reallocation on assignment: If an intrinsic assignment is used, an allocatable variable on the left-hand side is automatically allocated (if unallocated) or reallocated (if the shape is different). Currently, scalar deferred character length left-hand sides are correctly handled but arrays are not yet fully implemented.

  * Deferred-length character variables and scalar deferred-length character components of derived types are supported. (Note that array-valued compoents are not yet implemented.)

  * Transferring of allocations via MOVE_ALLOC.

  * The PRIVATE and PUBLIC attributes may be given individually to derived-type components.

  * In pointer assignments, the lower bound may be specified and the remapping of elements is supported.

  * For pointers an INTENT may be specified which affect the association status not the value of the pointer target.

  * Intrinsics command_argument_count, get_command, get_command_argument, and get_environment_variable.

  * Support for Unicode characters (ISO 10646) and UTF-8, including the SELECTED_CHAR_KIND and NEW_LINE intrinsic functions.

  * Support for binary, octal and hexadecimal (BOZ) constants in the intrinsic functions INT, REAL, CMPLX and DBLE.

  * Support for namelist variables with allocatable and pointer attribute and nonconstant length type parameter.

  * Array constructors using square brackets.  That is, [...] rather than (/.../).  Type-specification for array constructors like (/ some-type :: ... /).

  * Extensions to the specification and initialization expressions, including the support for intrinsics with real and complex arguments.

  * Support for the asynchronous input/output syntax; however, the data transfer is currently always synchronously performed.

  * FLUSH statement.

  * IOMSG= specifier for I/O statements.

  * Support for the declaration of enumeration constants via the ENUM and ENUMERATOR statements.  Interoperability with gcc is guaranteed also for the case where the -fshort-enums command line option is given.

  * TR 15581:

       * ALLOCATABLE dummy arguments.

       * ALLOCATABLE function results

       * ALLOCATABLE components of derived types

  * The OPEN statement supports the ACCESS='STREAM' specifier, allowing I/O without any record structure.

  * Namelist input/output for internal files.

  * Minor I/O features: Rounding during formatted output, using of a decimal comma instead of a decimal point, setting whether a plus sign should appear for positive numbers. On systems where strtod honours the rounding mode, the rounding mode is also supported for input.

  * The PROTECTED statement and attribute.

  * The VALUE statement and attribute.

  * The VOLATILE statement and attribute.

  * The IMPORT statement, allowing to import host-associated derived types.

  * The intrinsic modules ISO_FORTRAN_ENVIRONMENT is supported, which contains parameters of the I/O units, storage sizes. Additionally, procedures for C interoperability are available in the ISO_C_BINDING module.

  * USE statement with INTRINSIC and NON_INTRINSIC attribute; supported intrinsic modules: ISO_FORTRAN_ENV, ISO_C_BINDING, OMP_LIB and OMP_LIB_KINDS, and OPENACC.

  * Renaming of operators in the USE statement.

Fortran 2008 status
===================

The latest version of the Fortran standard is ISO/IEC 1539-1:2010, informally known as Fortran 2008.  The official version is available from International Organization for Standardization (ISO) or its national member organizations. The the final draft (FDIS) can be downloaded free of charge from http://www.nag.co.uk/sc22wg5/links.html.  Fortran is developed by the Working Group 5 of Sub-Committee 22 of the Joint Technical Committee 1 of the International Organization for Standardization and the International Electrotechnical Commission (IEC).  This group is known as WG5 (http://www.nag.co.uk/sc22wg5/).

The GNU Fortran compiler supports several of the new features of Fortran 2008; the wiki (https://gcc.gnu.org/wiki/Fortran2008Status) has some information about the current Fortran 2008 implementation status.  In particular, the following is implemented.

  * The -std=f2008 option and support for the file extensions .f08 and .F08.

  * The OPEN statement now supports the NEWUNIT= option, which returns a unique file unit, thus preventing inadvertent use of the same unit in different parts of the program.

  * The g0 format descriptor and unlimited format items.

  * The mathematical intrinsics ASINH, ACOSH, ATANH, ERF, ERFC, GAMMA, LOG_GAMMA, BESSEL_J0, BESSEL_J1, BESSEL_JN, BESSEL_Y0, BESSEL_Y1, BESSEL_YN, HYPOT, NORM2, and ERFC_SCALED.

  * Using complex arguments with TAN, SINH, COSH, TANH, ASIN, ACOS, and ATAN is now possible; ATAN(Y,X) is now an alias for ATAN2(Y,X).

  * Support of the PARITY intrinsic functions.

  * The following bit intrinsics: LEADZ and TRAILZ for counting the number of leading and trailing zero bits, POPCNT and POPPAR for counting the number of one bits and returning the parity; BGE, BGT, BLE, and BLT for bitwise comparisons; DSHIFTL and DSHIFTR for combined left and right shifts, MASKL and MASKR for simple left and right justified masks, MERGE_BITS for a bitwise merge using a mask, SHIFTA, SHIFTL and SHIFTR for shift operations, and the transformational bit intrinsics IALL, IANY and IPARITY.

  * Support of the EXECUTE_COMMAND_LINE intrinsic subroutine.

  * Support for the STORAGE_SIZE intrinsic inquiry function.

  * The INT{8,16,32} and REAL{32,64,128} kind type parameters and the array-valued named constants INTEGER_KINDS, LOGICAL_KINDS, REAL_KINDS and CHARACTER_KINDS of the intrinsic module ISO_FORTRAN_ENV.

  * The module procedures C_SIZEOF of the intrinsic module ISO_C_BINDINGS and COMPILER_VERSION and COMPILER_OPTIONS of ISO_FORTRAN_ENV.

  * Coarray support for serial programs with -fcoarray=single flag and experimental support for multiple images with the -fcoarray=lib flag.

  * The DO CONCURRENT construct is supported.

  * The BLOCK construct is supported.

  * The STOP and the new ERROR STOP statements now support all constant expressions. Both show the signals which were signaling at termination.

  * Support for the CONTIGUOUS attribute.

  * Support for ALLOCATE with MOLD.

  * Support for the IMPURE attribute for procedures, which allows for ELEMENTAL procedures without the restrictions of PURE.

  * Null pointers (including NULL()) and not-allocated variables can be used as actual argument to optional non-pointer, non-allocatable dummy arguments, denoting an absent argument.

  * Non-pointer variables with TARGET attribute can be used as actual argument to POINTER dummies with INTENT(IN).

  * Pointers including procedure pointers and those in a derived type (pointer components) can now be initialized by a target instead of only by NULL.

  * The EXIT statement (with construct-name) can be now be used to leave not only the DO but also the ASSOCIATE, BLOCK, IF, SELECT CASE and SELECT TYPE constructs.

  * Internal procedures can now be used as actual argument.

  * Minor features: obsolesce diagnostics for ENTRY with -std=f2008; a line may start with a semicolon; for internal and module procedures END can be used instead of END SUBROUTINE and END FUNCTION; SELECTED_REAL_KIND now also takes a RADIX argument; intrinsic types are supported for TYPE(INTRINSIC-TYPE-SPEC); multiple type-bound procedures can be declared in a single PROCEDURE statement; implied-shape arrays are supported for named constants (PARAMETER).

Technical Specification 29113 Status
====================================

GNU Fortran supports some of the new features of the Technical Specification (TS) 29113 on Further Interoperability of Fortran with C. The wiki (https://gcc.gnu.org/wiki/TS29113Status) has some information about the current TS 29113 implementation status.  In particular, the following is implemented.

See also Further Interoperability of Fortran with C.

  * The -std=f2008ts option.

  * The OPTIONAL attribute is allowed for dummy arguments of BIND(C) procedures.

  * The RANK intrinsic is supported.

  * GNU Fortran's implementation for variables with ASYNCHRONOUS attribute is compatible with TS 29113.

  * Assumed types (TYPE(*).

  * Assumed-rank (DIMENSION(..)). However, the array descriptor of the TS is not yet supported.

Compiler Characteristics
************************

This chapter describes certain characteristics of the GNU Fortran compiler, that are not specified by the Fortran standard, but which might in some way or another become visible to the programmer.

KIND Type Parameters
====================

The KIND type parameters supported by GNU Fortran for the primitive data types are:

INTEGER
     1, 2, 4, 8*, 16*, default: 4**

LOGICAL
     1, 2, 4, 8*, 16*, default: 4**

REAL
     4, 8, 10*, 16*, default: 4***

COMPLEX
     4, 8, 10*, 16*, default: 4***

DOUBLE PRECISION
     4, 8, 10*, 16*, default: 8***

CHARACTER
     1, 4, default: 1

* not available on all systems

** unless -fdefault-integer-8 is used

*** unless -fdefault-real-8 is used (see Fortran Dialect Options)

The KIND value matches the storage size in bytes, except for COMPLEX where the storage size is twice as much (or both real and imaginary part are a real value of the given size).  It is recommended to use the SELECTED_CHAR_KIND, SELECTED_INT_KIND and SELECTED_REAL_KIND intrinsics or the INT8, INT16, INT32, INT64, REAL32, REAL64, and REAL128 parameters of the ISO_FORTRAN_ENV module instead of the concrete values. The available kind parameters can be found in the constant arrays CHARACTER_KINDS, INTEGER_KINDS, LOGICAL_KINDS and REAL_KINDS in the ISO_FORTRAN_ENV module.  For C interoperability, the kind parameters of the ISO_C_BINDING module should be used.

Internal representation of LOGICAL variables
============================================

The Fortran standard does not specify how variables of LOGICAL type are represented, beyond requiring that LOGICAL variables of default kind have the same storage size as default INTEGER and REAL variables.  The GNU Fortran internal representation is as follows.

A LOGICAL(KIND=N) variable is represented as an INTEGER(KIND=N) variable, however, with only two permissible values: 1 for .TRUE. and 0 for .FALSE..  Any other integer value results in undefined behavior.

See also Argument passing conventions and Interoperability with C.

Thread-safety of the runtime library
====================================

GNU Fortran can be used in programs with multiple threads, e.g. by using OpenMP, by calling OS thread handling functions via the ISO_C_BINDING facility, or by GNU Fortran compiled library code being called from a multi-threaded program.

The GNU Fortran runtime library, (libgfortran), supports being called concurrently from multiple threads with the following exceptions.

During library initialization, the C getenv function is used, which need not be thread-safe.  Similarly, the getenv function is used to implement the GET_ENVIRONMENT_VARIABLE and GETENV intrinsics.  It is the responsibility of the user to ensure that the environment is not being updated concurrently when any of these actions are taking place.

The EXECUTE_COMMAND_LINE and SYSTEM intrinsics are implemented with the system function, which need not be thread-safe.  It is the responsibility of the user to ensure that system is not called concurrently.

For platforms not supporting thread-safe POSIX functions, further functionality might not be thread-safe.  For details, please consult the documentation for your operating system.

The GNU Fortran runtime library uses various C library functions that depend on the locale, such as strtod and snprintf.  In order to work correctly in locale-aware programs that set the locale using setlocale, the locale is reset to the default ``C'' locale while executing a formatted READ or WRITE statement.  On targets supporting the POSIX 2008 per-thread locale functions (e.g. newlocale, uselocale, freelocale), these are used and thus the global locale set using setlocale or the per-thread locales in other threads are not affected.  However, on targets lacking this functionality, the global LC_NUMERIC locale is set to ``C'' during the formatted I/O. Thus, on such targets it's not safe to call setlocale concurrently from another thread while a Fortran formatted I/O operation is in progress.  Also, other threads doing something dependent on the LC_NUMERIC locale might not work correctly if a formatted I/O operation is in progress in another thread.

Data consistency and durability
===============================

This section contains a brief overview of data and metadata consistency and durability issues when doing I/O.

With respect to durability, GNU Fortran makes no effort to ensure that data is committed to stable storage. If this is required, the GNU Fortran programmer can use the intrinsic FNUM to retrieve the low level file descriptor corresponding to an open Fortran unit. Then, using e.g. the ISO_C_BINDING feature, one can call the underlying system call to flush dirty data to stable storage, such as fsync on POSIX, _commit on MingW, or fcntl(fd, F_FULLSYNC, 0) on Mac OS X. The following example shows how to call fsync:

       ! Declare the interface for POSIX fsync function
       interface
         function fsync (fd) bind(c,name="fsync")
         use iso_c_binding, only: c_int
           integer(c_int), value :: fd
           integer(c_int) :: fsync
         end function fsync
       end interface

       ! Variable declaration
       integer :: ret

       ! Opening unit 10
       open (10,file="foo")

       ! ...
       ! Perform I/O on unit 10
       ! ...

       ! Flush and sync
       flush(10)
       ret = fsync(fnum(10))

       ! Handle possible error
       if (ret /= 0) stop "Error calling FSYNC"

With respect to consistency, for regular files GNU Fortran uses buffered I/O in order to improve performance. This buffer is flushed automatically when full and in some other situations, e.g. when closing a unit. It can also be explicitly flushed with the FLUSH statement. Also, the buffering can be turned off with the GFORTRAN_UNBUFFERED_ALL and GFORTRAN_UNBUFFERED_PRECONNECTED environment variables. Special files, such as terminals and pipes, are always unbuffered. Sometimes, however, further things may need to be done in order to allow other processes to see data that GNU Fortran has written, as follows.

The Windows platform supports a relaxed metadata consistency model, where file metadata is written to the directory lazily. This means that, for instance, the dir command can show a stale size for a file. One can force a directory metadata update by closing the unit, or by calling _commit on the file descriptor. Note, though, that _commit will force all dirty data to stable storage, which is often a very slow operation.

The Network File System (NFS) implements a relaxed consistency model called open-to-close consistency. Closing a file forces dirty data and metadata to be flushed to the server, and opening a file forces the client to contact the server in order to revalidate cached data. fsync will also force a flush of dirty data and metadata to the server. Similar to open and close, acquiring and releasing fcntl file locks, if the server supports them, will also force cache validation and flushing dirty data and metadata.

Files opened without an explicit ACTION= specifier
==================================================

The Fortran standard says that if an OPEN statement is executed without an explicit ACTION= specifier, the default value is processor dependent.  GNU Fortran behaves as follows:

 1. Attempt to open the file with ACTION='READWRITE'

 2. If that fails, try to open with ACTION='READ'

 3. If that fails, try to open with ACTION='WRITE'

 4. If that fails, generate an error

Extensions
**********

The two sections below detail the extensions to standard Fortran that are implemented in GNU Fortran, as well as some of the popular or historically important extensions that are not (or not yet) implemented. For the latter case, we explain the alternatives available to GNU Fortran users, including replacement by standard-conforming code or GNU extensions.

Extensions implemented in GNU Fortran
=====================================

GNU Fortran implements a number of extensions over standard Fortran.  This chapter contains information on their syntax and meaning.  There are currently two categories of GNU Fortran extensions, those that provide functionality beyond that provided by any standard, and those that are supported by GNU Fortran purely for backward compatibility with legacy compilers.  By default, -std=gnu allows the compiler to accept both types of extensions, but to warn about the use of the latter.  Specifying either -std=f95, -std=f2003 or -std=f2008 disables both types of extensions, and -std=legacy allows both without warning.

Old-style kind specifications
-----------------------------

GNU Fortran allows old-style kind specifications in declarations.  These look like:

           TYPESPEC*size x,y,z

where TYPESPEC is a basic type (INTEGER, REAL, etc.), and where size is a byte count corresponding to the storage size of a valid kind for that type.  (For COMPLEX variables, size is the total size of the real and imaginary parts.)  The statement then declares x, y and z to be of type TYPESPEC with the appropriate kind.  This is equivalent to the standard-conforming declaration

           TYPESPEC(k) x,y,z

where k is the kind parameter suitable for the intended precision.  As kind parameters are implementation-dependent, use the KIND, SELECTED_INT_KIND and SELECTED_REAL_KIND intrinsics to retrieve the correct value, for instance REAL*8 x can be replaced by:

     INTEGER, PARAMETER :: dbl = KIND(1.0d0)
     REAL(KIND=dbl) :: x

Old-style variable initialization
---------------------------------

GNU Fortran allows old-style initialization of variables of the form:

           INTEGER i/1/,j/2/
           REAL x(2,2) /3*0.,1./

The syntax for the initializers is as for the DATA statement, but unlike in a DATA statement, an initializer only applies to the variable immediately preceding the initialization.  In other words, something like INTEGER I,J/2,3/ is not valid.  This style of initialization is only allowed in declarations without double colons (::); the double colons were introduced in Fortran 90, which also introduced a standard syntax for initializing variables in type declarations.

Examples of standard-conforming code equivalent to the above example are:

     ! Fortran 90
           INTEGER :: i = 1, j = 2
           REAL :: x(2,2) = RESHAPE((/0.,0.,0.,1./),SHAPE(x))
     ! Fortran 77
           INTEGER i, j
           REAL x(2,2)
           DATA i/1/, j/2/, x/3*0.,1./

Note that variables which are explicitly initialized in declarations or in DATA statements automatically acquire the SAVE attribute.

Extensions to namelist
----------------------

GNU Fortran fully supports the Fortran 95 standard for namelist I/O including array qualifiers, substrings and fully qualified derived types. The output from a namelist write is compatible with namelist read.  The output has all names in upper case and indentation to column 1 after the namelist name.  Two extensions are permitted:

Old-style use of $ instead of &

     $MYNML
      X(:)%Y(2) = 1.0 2.0 3.0
      CH(1:4) = "abcd"
     $END

It should be noted that the default terminator is / rather than &END.

Querying of the namelist when inputting from stdin.  After at least one space, entering ? sends to stdout the namelist name and the names of the variables in the namelist:

      ?

     &mynml
      x
      x%y
      ch
     &end

Entering =? outputs the namelist to stdout, as if WRITE(*,NML = mynml) had been called:

     =?

     &MYNML
      X(1)%Y=  0.000000    ,  1.000000    ,  0.000000    ,
      X(2)%Y=  0.000000    ,  2.000000    ,  0.000000    ,
      X(3)%Y=  0.000000    ,  3.000000    ,  0.000000    ,
      CH=abcd,  /

To aid this dialog, when input is from stdin, errors send their messages to stderr and execution continues, even if IOSTAT is set.

PRINT namelist is permitted.  This causes an error if -std=f95 is used.

     PROGRAM test_print
       REAL, dimension (4)  ::  x = (/1.0, 2.0, 3.0, 4.0/)
       NAMELIST /mynml/ x
       PRINT mynml
     END PROGRAM test_print

Expanded namelist reads are permitted.  This causes an error if -std=f95 is used.  In the following example, the first element of the array will be given the value 0.00 and the two succeeding elements will be given the values 1.00 and 2.00.

     &MYNML
       X(1,1) = 0.00 , 1.00 , 2.00
     /

When writing a namelist, if no DELIM= is specified, by default a double quote is used to delimit character strings. If -std=F95, F2003, or F2008, etc, the delim status is set to 'none'.  Defaulting to quotes ensures that namelists with character strings can be subsequently read back in accurately.

X format descriptor without count field
---------------------------------------

To support legacy codes, GNU Fortran permits the count field of the X edit descriptor in FORMAT statements to be omitted. When omitted, the count is implicitly assumed to be one.

            PRINT 10, 2, 3
     10     FORMAT (I1, X, I1)

Commas in FORMAT specifications
-------------------------------

To support legacy codes, GNU Fortran allows the comma separator to be omitted immediately before and after character string edit descriptors in FORMAT statements.

            PRINT 10, 2, 3
     10     FORMAT ('FOO='I1' BAR='I2)

Missing period in FORMAT specifications
---------------------------------------

To support legacy codes, GNU Fortran allows missing periods in format specifications if and only if -std=legacy is given on the command line.  This is considered non-conforming code and is discouraged.

            REAL :: value
            READ(*,10) value
     10     FORMAT ('F4')

I/O item lists
--------------

To support legacy codes, GNU Fortran allows the input item list of the READ statement, and the output item lists of the WRITE and PRINT statements, to start with a comma.

Q exponent-letter
-----------------

GNU Fortran accepts real literal constants with an exponent-letter of Q, for example, 1.23Q45.  The constant is interpreted as a REAL(16) entity on targets that support this type.  If the target does not support REAL(16) but has a REAL(10) type, then the real-literal-constant will be interpreted as a REAL(10) entity.  In the absence of REAL(16) and REAL(10), an error will occur.

BOZ literal constants
---------------------

Besides decimal constants, Fortran also supports binary (b), octal (o) and hexadecimal (z) integer constants.  The syntax is: prefix quote digits quote, were the prefix is either b, o or z, quote is either ' or " and the digits are for binary 0 or 1, for octal between 0 and 7, and for hexadecimal between 0 and F.  (Example: b'01011101'.)

Up to Fortran 95, BOZ literals were only allowed to initialize integer variables in DATA statements.  Since Fortran 2003 BOZ literals are also allowed as argument of REAL, DBLE, INT and CMPLX; the result is the same as if the integer BOZ literal had been converted by TRANSFER to, respectively, real, double precision, integer or complex. As GNU Fortran extension the intrinsic procedures FLOAT, DFLOAT, COMPLEX and DCMPLX are treated alike.

As an extension, GNU Fortran allows hexadecimal BOZ literal constants to be specified using the X prefix, in addition to the standard Z prefix.  The BOZ literal can also be specified by adding a suffix to the string, for example, Z'ABC' and 'ABC'Z are equivalent.

Furthermore, GNU Fortran allows using BOZ literal constants outside DATA statements and the four intrinsic functions allowed by Fortran 2003. In DATA statements, in direct assignments, where the right-hand side only contains a BOZ literal constant, and for old-style initializers of the form integer i /o'0173'/, the constant is transferred as if TRANSFER had been used; for COMPLEX numbers, only the real part is initialized unless CMPLX is used.  In all other cases, the BOZ literal constant is converted to an INTEGER value with the largest decimal representation.  This value is then converted numerically to the type and kind of the variable in question. (For instance, real :: r = b'0000001' + 1 initializes r with 2.0.) As different compilers implement the extension differently, one should be careful when doing bitwise initialization of non-integer variables.

Note that initializing an INTEGER variable with a statement such as DATA i/Z'FFFFFFFF'/ will give an integer overflow error rather than the desired result of -1 when i is a 32-bit integer on a system that supports 64-bit integers.  The -fno-range-check option can be used as a workaround for legacy code that initializes integers in this manner.

Real array indices
------------------

As an extension, GNU Fortran allows the use of REAL expressions or variables as array indices.

Unary operators
---------------

As an extension, GNU Fortran allows unary plus and unary minus operators to appear as the second operand of binary arithmetic operators without the need for parenthesis.

            X = Y * -Z

Implicitly convert LOGICAL and INTEGER values
---------------------------------------------

As an extension for backwards compatibility with other compilers, GNU Fortran allows the implicit conversion of LOGICAL values to INTEGER values and vice versa.  When converting from a LOGICAL to an INTEGER, .FALSE. is interpreted as zero, and .TRUE. is interpreted as one.  When converting from INTEGER to LOGICAL, the value zero is interpreted as .FALSE. and any nonzero value is interpreted as .TRUE..

             LOGICAL :: l
             l = 1

             INTEGER :: i
             i = .TRUE.

However, there is no implicit conversion of INTEGER values in if-statements, nor of LOGICAL or INTEGER values in I/O operations.

Hollerith constants support
---------------------------

GNU Fortran supports Hollerith constants in assignments, function arguments, and DATA and ASSIGN statements.  A Hollerith constant is written as a string of characters preceded by an integer constant indicating the character count, and the letter H or h, and stored in bytewise fashion in a numeric (INTEGER, REAL, or complex) or LOGICAL variable.  The constant will be padded or truncated to fit the size of the variable in which it is stored.

Examples of valid uses of Hollerith constants:

           complex*16 x(2)
           data x /16Habcdefghijklmnop, 16Hqrstuvwxyz012345/
           x(1) = 16HABCDEFGHIJKLMNOP
           call foo (4h abc)

Invalid Hollerith constants examples:

           integer*4 a
           a = 8H12345678 ! Valid, but the Hollerith constant will be truncated.
           a = 0H         ! At least one character is needed.

In general, Hollerith constants were used to provide a rudimentary facility for handling character strings in early Fortran compilers, prior to the introduction of CHARACTER variables in Fortran 77; in those cases, the standard-compliant equivalent is to convert the program to use proper character strings.  On occasion, there may be a case where the intent is specifically to initialize a numeric variable with a given byte sequence.  In these cases, the same result can be obtained by using the TRANSFER statement, as in this example.

           INTEGER(KIND=4) :: a
           a = TRANSFER ("abcd", a)     ! equivalent to: a = 4Habcd

Cray pointers
-------------

Cray pointers are part of a non-standard extension that provides a C-like pointer in Fortran.  This is accomplished through a pair of variables: an integer "pointer" that holds a memory address, and a "pointee" that is used to dereference the pointer.

Pointer/pointee pairs are declared in statements of the form:

             pointer ( <pointer> , <pointee> )

or,

             pointer ( <pointer1> , <pointee1> ), ( <pointer2> , <pointee2> ), ...

The pointer is an integer that is intended to hold a memory address. The pointee may be an array or scalar.  A pointee can be an assumed size array---that is, the last dimension may be left unspecified by using a * in place of a value---but a pointee cannot be an assumed shape array.  No space is allocated for the pointee.

The pointee may have its type declared before or after the pointer statement, and its array specification (if any) may be declared before, during, or after the pointer statement.  The pointer may be declared as an integer prior to the pointer statement.  However, some machines have default integer sizes that are different than the size of a pointer, and so the following code is not portable:

             integer ipt
             pointer (ipt, iarr)

If a pointer is declared with a kind that is too small, the compiler will issue a warning; the resulting binary will probably not work correctly, because the memory addresses stored in the pointers may be truncated.  It is safer to omit the first line of the above example; if explicit declaration of ipt's type is omitted, then the compiler will ensure that ipt is an integer variable large enough to hold a pointer.

Pointer arithmetic is valid with Cray pointers, but it is not the same as C pointer arithmetic.  Cray pointers are just ordinary integers, so the user is responsible for determining how many bytes to add to a pointer in order to increment it.  Consider the following example:

             real target(10)
             real pointee(10)
             pointer (ipt, pointee)
             ipt = loc (target)
             ipt = ipt + 1

The last statement does not set ipt to the address of target(1), as it would in C pointer arithmetic.  Adding 1 to ipt just adds one byte to the address stored in ipt.

Any expression involving the pointee will be translated to use the value stored in the pointer as the base address.

To get the address of elements, this extension provides an intrinsic function LOC().  The LOC() function is equivalent to the & operator in C, except the address is cast to an integer type:

             real ar(10)
             pointer(ipt, arpte(10))
             real arpte
             ipt = loc(ar)  ! Makes arpte is an alias for ar
             arpte(1) = 1.0 ! Sets ar(1) to 1.0

The pointer can also be set by a call to the MALLOC intrinsic (see MALLOC).

Cray pointees often are used to alias an existing variable.  For example:

             integer target(10)
             integer iarr(10)
             pointer (ipt, iarr)
             ipt = loc(target)

As long as ipt remains unchanged, iarr is now an alias for target.  The optimizer, however, will not detect this aliasing, so it is unsafe to use iarr and target simultaneously.  Using a pointee in any way that violates the Fortran aliasing rules or assumptions is illegal.  It is the user's responsibility to avoid doing this; the compiler works under the assumption that no such aliasing occurs.

Cray pointers will work correctly when there is no aliasing (i.e., when they are used to access a dynamically allocated block of memory), and also in any routine where a pointee is used, but any variable with which it shares storage is not used.  Code that violates these rules may not run as the user intends.  This is not a bug in the optimizer; any code that violates the aliasing rules is illegal.  (Note that this is not unique to GNU Fortran; any Fortran compiler that supports Cray pointers will ``incorrectly'' optimize code with illegal aliasing.)

There are a number of restrictions on the attributes that can be applied to Cray pointers and pointees.  Pointees may not have the ALLOCATABLE, INTENT, OPTIONAL, DUMMY, TARGET, INTRINSIC, or POINTER attributes.  Pointers may not have the DIMENSION, POINTER, TARGET, ALLOCATABLE, EXTERNAL, or INTRINSIC attributes, nor may they be function results.  Pointees may not occur in more than one pointer statement.  A pointee cannot be a pointer.  Pointees cannot occur in equivalence, common, or data statements.

A Cray pointer may also point to a function or a subroutine.  For example, the following excerpt is valid:

       implicit none
       external sub
       pointer (subptr,subpte)
       external subpte
       subptr = loc(sub)
       call subpte()
       [...]
       subroutine sub
       [...]
       end subroutine sub

A pointer may be modified during the course of a program, and this will change the location to which the pointee refers.  However, when pointees are passed as arguments, they are treated as ordinary variables in the invoked function.  Subsequent changes to the pointer will not change the base address of the array that was passed.

CONVERT specifier
-----------------

GNU Fortran allows the conversion of unformatted data between little- and big-endian representation to facilitate moving of data between different systems.  The conversion can be indicated with the CONVERT specifier on the OPEN statement. See GFORTRAN_CONVERT_UNIT, for an alternative way of specifying the data format via an environment variable.

Valid values for CONVERT are:

  CONVERT='NATIVE' Use the native format.  This is the default.

  CONVERT='SWAP' Swap between little- and big-endian.

  CONVERT='LITTLE_ENDIAN' Use the little-endian representation for unformatted files.

  CONVERT='BIG_ENDIAN' Use the big-endian representation for unformatted files.

Using the option could look like this:

       open(file='big.dat',form='unformatted',access='sequential', &
            convert='big_endian')

The value of the conversion can be queried by using INQUIRE(CONVERT=ch).  The values returned are 'BIG_ENDIAN' and 'LITTLE_ENDIAN'.

CONVERT works between big- and little-endian for INTEGER values of all supported kinds and for REAL on IEEE systems of kinds 4 and 8.  Conversion between different ``extended double'' types on different architectures such as m68k and x86_64, which GNU Fortran supports as REAL(KIND=10) and REAL(KIND=16), will probably not work.

Note that the values specified via the GFORTRAN_CONVERT_UNIT environment variable will override the CONVERT specifier in the open statement.  This is to give control over data formats to users who do not have the source code of their program available.

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.

OpenMP
------

OpenMP (Open Multi-Processing) is an application programming interface (API) that supports multi-platform shared memory multiprocessing programming in C/C++ and Fortran on many architectures, including Unix and Microsoft Windows platforms. It consists of a set of compiler directives, library routines, and environment variables that influence run-time behavior.

GNU Fortran strives to be compatible to the OpenMP Application Program Interface v4.0 (http://openmp.org/wp/openmp-specifications/).

To enable the processing of the OpenMP directive !$omp in free-form source code; the c$omp, *$omp and !$omp directives in fixed form; the !$ conditional compilation sentinels in free form; and the c$, *$ and !$ sentinels in fixed form, gfortran needs to be invoked with the -fopenmp.  This also arranges for automatic linking of the GNU Offloading and Multi Processing Runtime Library libgomp (GNU Offloading and Multi Processing Runtime Library).

The OpenMP Fortran runtime library routines are provided both in a form of a Fortran 90 module named omp_lib and in a form of a Fortran include file named omp_lib.h.

An example of a parallelized loop taken from Appendix A.1 of the OpenMP Application Program Interface v2.5:

     SUBROUTINE A1(N, A, B)
       INTEGER I, N
       REAL B(N), A(N)
     !$OMP PARALLEL DO !I is private by default
       DO I=2,N
         B(I) = (A(I) + A(I-1)) / 2.0
       ENDDO
     !$OMP END PARALLEL DO
     END SUBROUTINE A1

Please note:

  * -fopenmp implies -frecursive, i.e., all local arrays will be allocated on the stack.  When porting existing code to OpenMP, this may lead to surprising results, especially to segmentation faults if the stacksize is limited.

  * On glibc-based systems, OpenMP enabled applications cannot be statically linked due to limitations of the underlying pthreads-implementation.  It might be possible to get a working solution if -Wl,--whole-archive -lpthread -Wl,--no-whole-archive is added to the command line.  However, this is not supported by gcc and thus not recommended.

OpenACC
-------

OpenACC is an application programming interface (API) that supports offloading of code to accelerator devices.  It consists of a set of compiler directives, library routines, and environment variables that influence run-time behavior.

GNU Fortran strives to be compatible to the OpenACC Application Programming Interface v2.0 (http://www.openacc.org/).

To enable the processing of the OpenACC directive !$acc in free-form source code; the c$acc, *$acc and !$acc directives in fixed form; the !$ conditional compilation sentinels in free form; and the c$, *$ and !$ sentinels in fixed form, gfortran needs to be invoked with the -fopenacc.  This also arranges for automatic linking of the GNU Offloading and Multi Processing Runtime Library libgomp (GNU Offloading and Multi Processing Runtime Library).

The OpenACC Fortran runtime library routines are provided both in a form of a Fortran 90 module named openacc and in a form of a Fortran include file named openacc_lib.h.

Note that this is an experimental feature, incomplete, and subject to change in future versions of GCC.  See https://gcc.gnu.org/wiki/OpenACC for more information.

Argument list functions %VAL, %REF and %LOC
-------------------------------------------

GNU Fortran supports argument list functions %VAL, %REF and %LOC statements, for backward compatibility with g77. It is recommended that these should be used only for code that is accessing facilities outside of GNU Fortran, such as operating system or windowing facilities.  It is best to constrain such uses to isolated portions of a program--portions that deal specifically and exclusively with low-level, system-dependent facilities.  Such portions might well provide a portable interface for use by the program as a whole, but are themselves not portable, and should be thoroughly tested each time they are rebuilt using a new compiler or version of a compiler.

%VAL passes a scalar argument by value, %REF passes it by reference and %LOC passes its memory location.  Since gfortran already passes scalar arguments by reference, %REF is in effect a do-nothing.  %LOC has the same effect as a Fortran pointer.

An example of passing an argument by value to a C subroutine foo.:

     C
     C prototype      void foo_ (float x);
     C
           external foo
           real*4 x
           x = 3.14159
           call foo (%VAL (x))
           end

For details refer to the g77 manual https://gcc.gnu.org/onlinedocs/gcc-3.4.6/g77/index.html#Top.

Also, c_by_val.f and its partner c_by_val.c of the GNU Fortran testsuite are worth a look.

Read/Write after EOF marker
---------------------------

Some legacy codes rely on allowing READ or WRITE after the EOF file marker in order to find the end of a file. GNU Fortran normally rejects these codes with a run-time error message and suggests the user consider BACKSPACE or REWIND to properly position the file before the EOF marker.  As an extension, the run-time error may be disabled using -std=legacy.

Extensions not implemented in GNU Fortran
=========================================

The long history of the Fortran language, its wide use and broad userbase, the large number of different compiler vendors and the lack of some features crucial to users in the first standards have lead to the existence of a number of important extensions to the language.  While some of the most useful or popular extensions are supported by the GNU Fortran compiler, not all existing extensions are supported.  This section aims at listing these extensions and offering advice on how best make code that uses them running with the GNU Fortran compiler.

STRUCTURE and RECORD
--------------------

Record structures are a pre-Fortran-90 vendor extension to create user-defined aggregate data types.  GNU Fortran does not support record structures, only Fortran 90's ``derived types'', which have a different syntax.

In many cases, record structures can easily be converted to derived types. To convert, replace STRUCTURE /STRUCTURE-NAME/ by TYPE TYPE-NAME.  Additionally, replace RECORD /STRUCTURE-NAME/ by TYPE(TYPE-NAME). Finally, in the component access, replace the period (.) by the percent sign (%).

Here is an example of code using the non portable record structure syntax:

     ! Declaring a structure named ``item'' and containing three fields:
     ! an integer ID, an description string and a floating-point price.
     STRUCTURE /item/
       INTEGER id
       CHARACTER(LEN=200) description
       REAL price
     END STRUCTURE

     ! Define two variables, an single record of type ``item''
     ! named ``pear'', and an array of items named ``store_catalog''
     RECORD /item/ pear, store_catalog(100)

     ! We can directly access the fields of both variables
     pear.id = 92316
     pear.description = "juicy D'Anjou pear"
     pear.price = 0.15
     store_catalog(7).id = 7831
     store_catalog(7).description = "milk bottle"
     store_catalog(7).price = 1.2

     ! We can also manipulate the whole structure
     store_catalog(12) = pear
     print *, store_catalog(12)

This code can easily be rewritten in the Fortran 90 syntax as following:

     ! ``STRUCTURE /name/ ... END STRUCTURE'' becomes
     ! ``TYPE name ... END TYPE''
     TYPE item
       INTEGER id
       CHARACTER(LEN=200) description
       REAL price
     END TYPE

     ! ``RECORD /name/ variable'' becomes ``TYPE(name) variable''
     TYPE(item) pear, store_catalog(100)

     ! Instead of using a dot (.) to access fields of a record, the
     ! standard syntax uses a percent sign (%)
     pear%id = 92316
     pear%description = "juicy D'Anjou pear"
     pear%price = 0.15
     store_catalog(7)%id = 7831
     store_catalog(7)%description = "milk bottle"
     store_catalog(7)%price = 1.2

     ! Assignments of a whole variable do not change
     store_catalog(12) = pear
     print *, store_catalog(12)

ENCODE and DECODE statements
----------------------------

GNU Fortran does not support the ENCODE and DECODE statements.  These statements are best replaced by READ and WRITE statements involving internal files (CHARACTER variables and arrays), which have been part of the Fortran standard since Fortran 77.  For example, replace a code fragment like

           INTEGER*1 LINE(80)
           REAL A, B, C
     c     ... Code that sets LINE
           DECODE (80, 9000, LINE) A, B, C
      9000 FORMAT (1X, 3(F10.5))

with the following:

           CHARACTER(LEN=80) LINE
           REAL A, B, C
     c     ... Code that sets LINE
           READ (UNIT=LINE, FMT=9000) A, B, C
      9000 FORMAT (1X, 3(F10.5))

Similarly, replace a code fragment like

           INTEGER*1 LINE(80)
           REAL A, B, C
     c     ... Code that sets A, B and C
           ENCODE (80, 9000, LINE) A, B, C
      9000 FORMAT (1X, 'OUTPUT IS ', 3(F10.5))

with the following:

           CHARACTER(LEN=80) LINE
           REAL A, B, C
     c     ... Code that sets A, B and C
           WRITE (UNIT=LINE, FMT=9000) A, B, C
      9000 FORMAT (1X, 'OUTPUT IS ', 3(F10.5))

Variable FORMAT expressions
---------------------------

A variable FORMAT expression is format statement which includes angle brackets enclosing a Fortran expression: FORMAT(I<N>).  GNU Fortran does not support this legacy extension.  The effect of variable format expressions can be reproduced by using the more powerful (and standard) combination of internal output and string formats.  For example, replace a code fragment like this:

           WRITE(6,20) INT1
      20   FORMAT(I<N+1>)

with the following:

     c     Variable declaration
           CHARACTER(LEN=20) FMT
     c
     c     Other code here...
     c
           WRITE(FMT,'("(I", I0, ")")') N+1
           WRITE(6,FMT) INT1

or with:

     c     Variable declaration
           CHARACTER(LEN=20) FMT
     c
     c     Other code here...
     c
           WRITE(FMT,*) N+1
           WRITE(6,"(I" // ADJUSTL(FMT) // ")") INT1

Alternate complex function syntax
---------------------------------

Some Fortran compilers, including g77, let the user declare complex functions with the syntax COMPLEX FUNCTION name*16(), as well as COMPLEX*16 FUNCTION name().  Both are non-standard, legacy extensions.  gfortran accepts the latter form, which is more common, but not the former.

Volatile COMMON blocks
----------------------

Some Fortran compilers, including g77, let the user declare COMMON with the VOLATILE attribute. This is invalid standard Fortran syntax and is not supported by gfortran.  Note that gfortran accepts VOLATILE variables in COMMON blocks since revision 4.3.

Mixed-Language Programming
**************************

This chapter is about mixed-language interoperability, but also applies if one links Fortran code compiled by different compilers.  In most cases, use of the C Binding features of the Fortran 2003 standard is sufficient, and their use is highly recommended.

Interoperability with C
=======================

Since Fortran 2003 (ISO/IEC 1539-1:2004(E)) there is a standardized way to generate procedure and derived-type declarations and global variables which are interoperable with C (ISO/IEC 9899:1999).  The bind(C) attribute has been added to inform the compiler that a symbol shall be interoperable with C; also, some constraints are added.  Note, however, that not all C features have a Fortran equivalent or vice versa.  For instance, neither C's unsigned integers nor C's functions with variable number of arguments have an equivalent in Fortran.

Note that array dimensions are reversely ordered in C and that arrays in C always start with index 0 while in Fortran they start by default with 1.  Thus, an array declaration A(n,m) in Fortran matches A[m][n] in C and accessing the element A(i,j) matches A[j-1][i-1].  The element following A(i,j) (C: A[j-1][i-1]; assuming i < n) in memory is A(i+1,j) (C: A[j-1][i]).

Intrinsic Types
---------------

In order to ensure that exactly the same variable type and kind is used in C and Fortran, the named constants shall be used which are defined in the ISO_C_BINDING intrinsic module.  That module contains named constants for kind parameters and character named constants for the escape sequences in C.  For a list of the constants, see ISO_C_BINDING.

For logical types, please note that the Fortran standard only guarantees interoperability between C99's _Bool and Fortran's C_Bool-kind logicals and C99 defines that true has the value 1 and false the value 0.  Using any other integer value with GNU Fortran's LOGICAL (with any kind parameter) gives an undefined result.  (Passing other integer values than 0 and 1 to GCC's _Bool is also undefined, unless the integer is explicitly or implicitly casted to _Bool.)

Derived Types and struct
------------------------

For compatibility of derived types with struct, one needs to use the BIND(C) attribute in the type declaration.  For instance, the following type declaration

      USE ISO_C_BINDING
      TYPE, BIND(C) :: myType
        INTEGER(C_INT) :: i1, i2
        INTEGER(C_SIGNED_CHAR) :: i3
        REAL(C_DOUBLE) :: d1
        COMPLEX(C_FLOAT_COMPLEX) :: c1
        CHARACTER(KIND=C_CHAR) :: str(5)
      END TYPE

matches the following struct declaration in C

      struct {
        int i1, i2;
        /* Note: "char" might be signed or unsigned.  */
        signed char i3;
        double d1;
        float _Complex c1;
        char str[5];
      } myType;

Derived types with the C binding attribute shall not have the sequence attribute, type parameters, the extends attribute, nor type-bound procedures.  Every component must be of interoperable type and kind and may not have the pointer or allocatable attribute.  The names of the components are irrelevant for interoperability.

As there exist no direct Fortran equivalents, neither unions nor structs with bit field or variable-length array members are interoperable.

Interoperable Global Variables
------------------------------

Variables can be made accessible from C using the C binding attribute, optionally together with specifying a binding name.  Those variables have to be declared in the declaration part of a MODULE, be of interoperable type, and have neither the pointer nor the allocatable attribute.

       MODULE m
         USE myType_module
         USE ISO_C_BINDING
         integer(C_INT), bind(C, name="_MyProject_flags") :: global_flag
         type(myType), bind(C) :: tp
       END MODULE

Here, _MyProject_flags is the case-sensitive name of the variable as seen from C programs while global_flag is the case-insensitive name as seen from Fortran.  If no binding name is specified, as for TP, the C binding name is the (lowercase) Fortran binding name. If a binding name is specified, only a single variable may be after the double colon.  Note of warning: You cannot use a global variable to access ERRNO of the C library as the C standard allows it to be a macro.  Use the IERRNO intrinsic (GNU extension) instead.

Interoperable Subroutines and Functions
---------------------------------------

Subroutines and functions have to have the BIND(C) attribute to be compatible with C.  The dummy argument declaration is relatively straightforward.  However, one needs to be careful because C uses call-by-value by default while Fortran behaves usually similar to call-by-reference.  Furthermore, strings and pointers are handled differently.  Note that in Fortran 2003 and 2008 only explicit size and assumed-size arrays are supported but not assumed-shape or deferred-shape (i.e. allocatable or pointer) arrays.  However, those are allowed since the Technical Specification 29113, see Further Interoperability of Fortran with C

To pass a variable by value, use the VALUE attribute. Thus, the following C prototype

     int func(int i, int *j)

matches the Fortran declaration

       integer(c_int) function func(i,j)
         use iso_c_binding, only: c_int
         integer(c_int), VALUE :: i
         integer(c_int) :: j

Note that pointer arguments also frequently need the VALUE attribute, see Working with Pointers.

Strings are handled quite differently in C and Fortran.  In C a string is a NUL-terminated array of characters while in Fortran each string has a length associated with it and is thus not terminated (by e.g. NUL).  For example, if one wants to use the following C function,

       #include <stdio.h>
       void print_C(char *string) /* equivalent: char string[]  */
       {
          printf("%s\n", string);
       }

to print ``Hello World'' from Fortran, one can call it using

       use iso_c_binding, only: C_CHAR, C_NULL_CHAR
       interface
         subroutine print_c(string) bind(C, name="print_C")
           use iso_c_binding, only: c_char
           character(kind=c_char) :: string(*)
         end subroutine print_c
       end interface
       call print_c(C_CHAR_"Hello World"//C_NULL_CHAR)

As the example shows, one needs to ensure that the string is NUL terminated.  Additionally, the dummy argument STRING of print_C is a length-one assumed-size array; using character(len=*) is not allowed.  The example above uses c_char_"Hello World" to ensure the string literal has the right type; typically the default character kind and c_char are the same and thus "Hello World" is equivalent.  However, the standard does not guarantee this.

The use of strings is now further illustrated using the C library function strncpy, whose prototype is

       char *strncpy(char *restrict s1, const char *restrict s2, size_t n);

The function strncpy copies at most N characters from string S2 to S1 and returns S1.  In the following example, we ignore the return value:

       use iso_c_binding
       implicit none
       character(len=30) :: str,str2
       interface
         ! Ignore the return value of strncpy -> subroutine
         ! "restrict" is always assumed if we do not pass a pointer
         subroutine strncpy(dest, src, n) bind(C)
           import
           character(kind=c_char),  intent(out) :: dest(*)
           character(kind=c_char),  intent(in)  :: src(*)
           integer(c_size_t), value, intent(in) :: n
         end subroutine strncpy
       end interface
       str = repeat('X',30) ! Initialize whole string with 'X'
       call strncpy(str, c_char_"Hello World"//C_NULL_CHAR, &
                    len(c_char_"Hello World",kind=c_size_t))
       print '(a)', str ! prints: "Hello WorldXXXXXXXXXXXXXXXXXXX"
       end

The intrinsic procedures are described in Intrinsic Procedures.

Working with Pointers
---------------------

C pointers are represented in Fortran via the special opaque derived type type(c_ptr) (with private components).  Thus one needs to use intrinsic conversion procedures to convert from or to C pointers.

For some applications, using an assumed type (TYPE(*)) can be an alternative to a C pointer; see Further Interoperability of Fortran with C.

For example,

       use iso_c_binding
       type(c_ptr) :: cptr1, cptr2
       integer, target :: array(7), scalar
       integer, pointer :: pa(:), ps
       cptr1 = c_loc(array(1)) ! The programmer needs to ensure that the
                               ! array is contiguous if required by the C
                               ! procedure
       cptr2 = c_loc(scalar)
       call c_f_pointer(cptr2, ps)
       call c_f_pointer(cptr2, pa, shape=[7])

When converting C to Fortran arrays, the one-dimensional SHAPE argument has to be passed.

If a pointer is a dummy-argument of an interoperable procedure, it usually has to be declared using the VALUE attribute.  void* matches TYPE(C_PTR), VALUE, while TYPE(C_PTR) alone matches void**.

Procedure pointers are handled analogously to pointers; the C type is TYPE(C_FUNPTR) and the intrinsic conversion procedures are C_F_PROCPOINTER and C_FUNLOC.

Let us consider two examples of actually passing a procedure pointer from C to Fortran and vice versa.  Note that these examples are also very similar to passing ordinary pointers between both languages. First, consider this code in C:

     /* Procedure implemented in Fortran.  */
     void get_values (void (*)(double));

     /* Call-back routine we want called from Fortran.  */
     void
     print_it (double x)
     {
       printf ("Number is %f.\n", x);
     }

     /* Call Fortran routine and pass call-back to it.  */
     void
     foobar ()
     {
       get_values (&print_it);
     }

A matching implementation for get_values in Fortran, that correctly receives the procedure pointer from C and is able to call it, is given in the following MODULE:

     MODULE m
       IMPLICIT NONE

       ! Define interface of call-back routine.
       ABSTRACT INTERFACE
         SUBROUTINE callback (x)
           USE, INTRINSIC :: ISO_C_BINDING
           REAL(KIND=C_DOUBLE), INTENT(IN), VALUE :: x
         END SUBROUTINE callback
       END INTERFACE

     CONTAINS

       ! Define C-bound procedure.
       SUBROUTINE get_values (cproc) BIND(C)
         USE, INTRINSIC :: ISO_C_BINDING
         TYPE(C_FUNPTR), INTENT(IN), VALUE :: cproc

         PROCEDURE(callback), POINTER :: proc

         ! Convert C to Fortran procedure pointer.
         CALL C_F_PROCPOINTER (cproc, proc)

         ! Call it.
         CALL proc (1.0_C_DOUBLE)
         CALL proc (-42.0_C_DOUBLE)
         CALL proc (18.12_C_DOUBLE)
       END SUBROUTINE get_values

     END MODULE m

Next, we want to call a C routine that expects a procedure pointer argument and pass it a Fortran procedure (which clearly must be interoperable!). Again, the C function may be:

     int
     call_it (int (*func)(int), int arg)
     {
       return func (arg);
     }

It can be used as in the following Fortran code:

     MODULE m
       USE, INTRINSIC :: ISO_C_BINDING
       IMPLICIT NONE

       ! Define interface of C function.
       INTERFACE
         INTEGER(KIND=C_INT) FUNCTION call_it (func, arg) BIND(C)
           USE, INTRINSIC :: ISO_C_BINDING
           TYPE(C_FUNPTR), INTENT(IN), VALUE :: func
           INTEGER(KIND=C_INT), INTENT(IN), VALUE :: arg
         END FUNCTION call_it
       END INTERFACE

     CONTAINS

       ! Define procedure passed to C function.
       ! It must be interoperable!
       INTEGER(KIND=C_INT) FUNCTION double_it (arg) BIND(C)
         INTEGER(KIND=C_INT), INTENT(IN), VALUE :: arg
         double_it = arg + arg
       END FUNCTION double_it

       ! Call C function.
       SUBROUTINE foobar ()
         TYPE(C_FUNPTR) :: cproc
         INTEGER(KIND=C_INT) :: i

         ! Get C procedure pointer.
         cproc = C_FUNLOC (double_it)

         ! Use it.
         DO i = 1_C_INT, 10_C_INT
           PRINT *, call_it (cproc, i)
         END DO
       END SUBROUTINE foobar

     END MODULE m

Further Interoperability of Fortran with C
------------------------------------------

The Technical Specification ISO/IEC TS 29113:2012 on further interoperability of Fortran with C extends the interoperability support of Fortran 2003 and Fortran 2008. Besides removing some restrictions and constraints, it adds assumed-type (TYPE(*)) and assumed-rank (dimension) variables and allows for interoperability of assumed-shape, assumed-rank and deferred-shape arrays, including allocatables and pointers.

Note: Currently, GNU Fortran does not support the array descriptor (dope vector) as specified in the Technical Specification, but uses an array descriptor with different fields. The Chasm Language Interoperability Tools, http://chasm-interop.sourceforge.net/, provide an interface to GNU Fortran's array descriptor.

The Technical Specification adds the following new features, which are supported by GNU Fortran:

  * The ASYNCHRONOUS attribute has been clarified and extended to allow its use with asynchronous communication in user-provided libraries such as in implementations of the Message Passing Interface specification.

  * Many constraints have been relaxed, in particular for the C_LOC and C_F_POINTER intrinsics.

  * The OPTIONAL attribute is now allowed for dummy arguments; an absent argument matches a NULL pointer.

  * Assumed types (TYPE(*)) have been added, which may only be used for dummy arguments.  They are unlimited polymorphic but contrary to CLASS(*) they do not contain any type information, similar to C's void * pointers.  Expressions of any type and kind can be passed; thus, it can be used as replacement for TYPE(C_PTR), avoiding the use of C_LOC in the caller.

     Note, however, that TYPE(*) only accepts scalar arguments, unless the DIMENSION is explicitly specified.  As DIMENSION(*) only supports array (including array elements) but no scalars, it is not a full replacement for C_LOC.  On the other hand, assumed-type assumed-rank dummy arguments (TYPE(*), DIMENSION(..)) allow for both scalars and arrays, but require special code on the callee side to handle the array descriptor.

  * Assumed-rank arrays (DIMENSION(..)) as dummy argument allow that scalars and arrays of any rank can be passed as actual argument. As the Technical Specification does not provide for direct means to operate with them, they have to be used either from the C side or be converted using C_LOC and C_F_POINTER to scalars or arrays of a specific rank. The rank can be determined using the RANK intrinisic.

Currently unimplemented:

  * GNU Fortran always uses an array descriptor, which does not match the one of the Technical Specification. The ISO_Fortran_binding.h header file and the C functions it specifies are not available.

  * Using assumed-shape, assumed-rank and deferred-shape arrays in BIND(C) procedures is not fully supported. In particular, C interoperable strings of other length than one are not supported as this requires the new array descriptor.

GNU Fortran Compiler Directives
===============================

The Fortran standard describes how a conforming program shall behave; however, the exact implementation is not standardized.  In order to allow the user to choose specific implementation details, compiler directives can be used to set attributes of variables and procedures which are not part of the standard.  Whether a given attribute is supported and its exact effects depend on both the operating system and on the processor; see C Extensions (Using the GNU Compiler Collection (GCC)) for details.

For procedures and procedure pointers, the following attributes can be used to change the calling convention:

  * CDECL -- standard C calling convention

  * STDCALL -- convention where the called procedure pops the stack

  * FASTCALL -- part of the arguments are passed via registers instead using the stack

Besides changing the calling convention, the attributes also influence the decoration of the symbol name, e.g., by a leading underscore or by a trailing at-sign followed by the number of bytes on the stack.  When assigning a procedure to a procedure pointer, both should use the same calling convention.

On some systems, procedures and global variables (module variables and COMMON blocks) need special handling to be accessible when they are in a shared library.  The following attributes are available:

  * DLLEXPORT -- provide a global pointer to a pointer in the DLL

  * DLLIMPORT -- reference the function or variable using a global pointer

For dummy arguments, the NO_ARG_CHECK attribute can be used; in other compilers, it is also known as IGNORE_TKR.  For dummy arguments with this attribute actual arguments of any type and kind (similar to TYPE(*)), scalars and arrays of any rank (no equivalent in Fortran standard) are accepted.  As with TYPE(*), the argument is unlimited polymorphic and no type information is available. Additionally, the argument may only be passed to dummy arguments with the NO_ARG_CHECK attribute and as argument to the PRESENT intrinsic function and to C_LOC of the ISO_C_BINDING module.

Variables with NO_ARG_CHECK attribute shall be of assumed-type (TYPE(*); recommended) or of type INTEGER, LOGICAL, REAL or COMPLEX. They shall not have the ALLOCATE, CODIMENSION, INTENT(OUT), POINTER or VALUE attribute; furthermore, they shall be either scalar or of assumed-size (dimension(*)). As TYPE(*), the NO_ARG_CHECK attribute requires an explicit interface.

  * NO_ARG_CHECK -- disable the type, kind and rank checking

The attributes are specified using the syntax

!GCC$ ATTRIBUTES ATTRIBUTE-LIST :: VARIABLE-LIST

where in free-form source code only whitespace is allowed before !GCC$ and in fixed-form source code !GCC$, cGCC$ or *GCC$ shall start in the first column.

For procedures, the compiler directives shall be placed into the body of the procedure; for variables and procedure pointers, they shall be in the same declaration part as the variable or procedure pointer.

Non-Fortran Main Program
========================

Even if you are doing mixed-language programming, it is very likely that you do not need to know or use the information in this section.  Since it is about the internal structure of GNU Fortran, it may also change in GCC minor releases.

When you compile a PROGRAM with GNU Fortran, a function with the name main (in the symbol table of the object file) is generated, which initializes the libgfortran library and then calls the actual program which uses the name MAIN__, for historic reasons.  If you link GNU Fortran compiled procedures to, e.g., a C or C++ program or to a Fortran program compiled by a different compiler, the libgfortran library is not initialized and thus a few intrinsic procedures do not work properly, e.g. those for obtaining the command-line arguments.

Therefore, if your PROGRAM is not compiled with GNU Fortran and the GNU Fortran compiled procedures require intrinsics relying on the library initialization, you need to initialize the library yourself.  Using the default options, gfortran calls _gfortran_set_args and _gfortran_set_options.  The initialization of the former is needed if the called procedures access the command line (and for backtracing); the latter sets some flags based on the standard chosen or to enable backtracing.  In typical programs, it is not necessary to call any initialization function.

If your PROGRAM is compiled with GNU Fortran, you shall not call any of the following functions.  The libgfortran initialization functions are shown in C syntax but using C bindings they are also accessible from Fortran.

_gfortran_set_args --- Save command-line arguments
--------------------------------------------------

Description:
     _gfortran_set_args saves the command-line arguments; this initialization is required if any of the command-line intrinsics is called.  Additionally, it shall be called if backtracing is enabled (see _gfortran_set_options).

Syntax:
     void _gfortran_set_args (int argc, char *argv[])

Arguments:

     ARGC   number of command line argument strings
     ARGV   the command-line argument strings; argv[0]
     is the pathname of the executable itself.

Example:

          int main (int argc, char *argv[])
          {
            /* Initialize libgfortran.  */
            _gfortran_set_args (argc, argv);
            return 0;
          }

_gfortran_set_options --- Set library option flags
--------------------------------------------------

Description:
     _gfortran_set_options sets several flags related to the Fortran standard to be used, whether backtracing should be enabled and whether range checks should be performed.  The syntax allows for upward compatibility since the number of passed flags is specified; for non-passed flags, the default value is used.  See also Code Gen Options.  Please note that not all flags are actually used.

Syntax:
     void _gfortran_set_options (int num, int options[])

Arguments:

     NUM   number of options passed
     ARGV   The list of flag values

option flag list:

     OPTION[0]   Allowed standard; can give run-time errors
     if e.g. an input-output edit descriptor is invalid in a given standard.
     Possible values are (bitwise or-ed) GFC_STD_F77 (1),
     GFC_STD_F95_OBS (2), GFC_STD_F95_DEL (4), GFC_STD_F95
     (8), GFC_STD_F2003 (16), GFC_STD_GNU (32),
     GFC_STD_LEGACY (64), GFC_STD_F2008 (128),
     GFC_STD_F2008_OBS (256) and GFC_STD_F2008_TS (512). Default:
     GFC_STD_F95_OBS | GFC_STD_F95_DEL | GFC_STD_F95 | GFC_STD_F2003
     | GFC_STD_F2008 | GFC_STD_F2008_TS | GFC_STD_F2008_OBS | GFC_STD_F77
     | GFC_STD_GNU | GFC_STD_LEGACY.
     OPTION[1]   Standard-warning flag; prints a warning to
     standard error.  Default: GFC_STD_F95_DEL | GFC_STD_LEGACY.
     OPTION[2]   If non zero, enable pedantic checking.
     Default: off.
     OPTION[3]   Unused.
     OPTION[4]   If non zero, enable backtracing on run-time
     errors.  Default: off. (Default in the compiler: on.)
     Note: Installs a signal handler and requires command-line
     initialization using _gfortran_set_args.
     OPTION[5]   If non zero, supports signed zeros.
     Default: enabled.
     OPTION[6]   Enables run-time checking.  Possible values
     are (bitwise or-ed): GFC_RTCHECK_BOUNDS (1), GFC_RTCHECK_ARRAY_TEMPS (2),
     GFC_RTCHECK_RECURSION (4), GFC_RTCHECK_DO (16), GFC_RTCHECK_POINTER (32).
     Default: disabled.
     OPTION[7]   Unused.
     OPTION[8]   Show a warning when invoking STOP and
     ERROR STOP if a floating-point exception occurred. Possible values
     are (bitwise or-ed) GFC_FPE_INVALID (1), GFC_FPE_DENORMAL (2),
     GFC_FPE_ZERO (4), GFC_FPE_OVERFLOW (8),
     GFC_FPE_UNDERFLOW (16), GFC_FPE_INEXACT (32). Default: None (0).
     (Default in the compiler: GFC_FPE_INVALID | GFC_FPE_DENORMAL |
     GFC_FPE_ZERO | GFC_FPE_OVERFLOW | GFC_FPE_UNDERFLOW.)

Example:

            /* Use gfortran 4.9 default options.  */
            static int options[] = {68, 511, 0, 0, 1, 1, 0, 0, 31};
            _gfortran_set_options (9, &options);

_gfortran_set_convert --- Set endian conversion
-----------------------------------------------

Description:
     _gfortran_set_convert set the representation of data for unformatted files.

Syntax:
     void _gfortran_set_convert (int conv)

Arguments:

     CONV   Endian conversion, possible values:
     GFC_CONVERT_NATIVE (0, default), GFC_CONVERT_SWAP (1),
     GFC_CONVERT_BIG (2), GFC_CONVERT_LITTLE (3).

Example:

          int main (int argc, char *argv[])
          {
            /* Initialize libgfortran.  */
            _gfortran_set_args (argc, argv);
            _gfortran_set_convert (1);
            return 0;
          }

_gfortran_set_record_marker --- Set length of record markers
------------------------------------------------------------

Description:
     _gfortran_set_record_marker sets the length of record markers for unformatted files.

Syntax:
     void _gfortran_set_record_marker (int val)

Arguments:

     VAL   Length of the record marker; valid values
     are 4 and 8.  Default is 4.

Example:

          int main (int argc, char *argv[])
          {
            /* Initialize libgfortran.  */
            _gfortran_set_args (argc, argv);
            _gfortran_set_record_marker (8);
            return 0;
          }

_gfortran_set_fpe --- Enable floating point exception traps
-----------------------------------------------------------

Description:
     _gfortran_set_fpe enables floating point exception traps for the specified exceptions.  On most systems, this will result in a SIGFPE signal being sent and the program being aborted.

Syntax:
     void _gfortran_set_fpe (int val)

Arguments:

     OPTION[0]   IEEE exceptions.  Possible values are
     (bitwise or-ed) zero (0, default) no trapping,
     GFC_FPE_INVALID (1), GFC_FPE_DENORMAL (2),
     GFC_FPE_ZERO (4), GFC_FPE_OVERFLOW (8),
     GFC_FPE_UNDERFLOW (16), and GFC_FPE_INEXACT (32).

Example:

          int main (int argc, char *argv[])
          {
            /* Initialize libgfortran.  */
            _gfortran_set_args (argc, argv);
            /* FPE for invalid operations such as SQRT(-1.0).  */
            _gfortran_set_fpe (1);
            return 0;
          }

_gfortran_set_max_subrecord_length --- Set subrecord length
-----------------------------------------------------------

Description:
     _gfortran_set_max_subrecord_length set the maximum length for a subrecord.  This option only makes sense for testing and debugging of unformatted I/O.

Syntax:
     void _gfortran_set_max_subrecord_length (int val)

Arguments:

     VAL   the maximum length for a subrecord;
     the maximum permitted value is 2147483639, which is also
     the default.

Example:

          int main (int argc, char *argv[])
          {
            /* Initialize libgfortran.  */
            _gfortran_set_args (argc, argv);
            _gfortran_set_max_subrecord_length (8);
            return 0;
          }

Naming and argument-passing conventions
=======================================

This section gives an overview about the naming convention of procedures and global variables and about the argument passing conventions used by GNU Fortran.  If a C binding has been specified, the naming convention and some of the argument-passing conventions change.  If possible, mixed-language and mixed-compiler projects should use the better defined C binding for interoperability.  See Interoperability with C.

Naming conventions
------------------

According the Fortran standard, valid Fortran names consist of a letter between A to Z, a to z, digits 0, 1 to 9 and underscores (_) with the restriction that names may only start with a letter.  As vendor extension, the dollar sign ($) is additionally permitted with the option -fdollar-ok, but not as first character and only if the target system supports it.

By default, the procedure name is the lower-cased Fortran name with an appended underscore (_); using -fno-underscoring no underscore is appended while -fsecond-underscore appends two underscores.  Depending on the target system and the calling convention, the procedure might be additionally dressed; for instance, on 32bit Windows with stdcall, an at-sign @ followed by an integer number is appended.  For the changing the calling convention, see GNU Fortran Compiler Directives.

For common blocks, the same convention is used, i.e. by default an underscore is appended to the lower-cased Fortran name.  Blank commons have the name __BLNK__.

For procedures and variables declared in the specification space of a module, the name is formed by __, followed by the lower-cased module name, _MOD_, and the lower-cased Fortran name.  Note that no underscore is appended.

Argument passing conventions
----------------------------

Subroutines do not return a value (matching C99's void) while functions either return a value as specified in the platform ABI or the result variable is passed as hidden argument to the function and no result is returned.  A hidden result variable is used when the result variable is an array or of type CHARACTER.

Arguments are passed according to the platform ABI. In particular, complex arguments might not be compatible to a struct with two real components for the real and imaginary part. The argument passing matches the one of C99's _Complex.  Functions with scalar complex result variables return their value and do not use a by-reference argument.  Note that with the -ff2c option, the argument passing is modified and no longer completely matches the platform ABI.  Some other Fortran compilers use f2c semantic by default; this might cause problems with interoperablility.

GNU Fortran passes most arguments by reference, i.e. by passing a pointer to the data.  Note that the compiler might use a temporary variable into which the actual argument has been copied, if required semantically (copy-in/copy-out).

For arguments with ALLOCATABLE and POINTER attribute (including procedure pointers), a pointer to the pointer is passed such that the pointer address can be modified in the procedure.

For dummy arguments with the VALUE attribute: Scalar arguments of the type INTEGER, LOGICAL, REAL and COMPLEX are passed by value according to the platform ABI. (As vendor extension and not recommended, using %VAL() in the call to a procedure has the same effect.) For TYPE(C_PTR) and procedure pointers, the pointer itself is passed such that it can be modified without affecting the caller.

For Boolean (LOGICAL) arguments, please note that GCC expects only the integer value 0 and 1.  If a GNU Fortran LOGICAL variable contains another integer value, the result is undefined. As some other Fortran compilers use -1 for .TRUE., extra care has to be taken -- such as passing the value as INTEGER.  (The same value restriction also applies to other front ends of GCC, e.g. to GCC's C99 compiler for _Bool or GCC's Ada compiler for Boolean.)

For arguments of CHARACTER type, the character length is passed as hidden argument.  For deferred-length strings, the value is passed by reference, otherwise by value.  The character length has the type INTEGER(kind=4).  Note with C binding, CHARACTER(len=1) result variables are returned according to the platform ABI and no hidden length argument is used for dummy arguments; with VALUE, those variables are passed by value.

For OPTIONAL dummy arguments, an absent argument is denoted by a NULL pointer, except for scalar dummy arguments of type INTEGER, LOGICAL, REAL and COMPLEX which have the VALUE attribute.  For those, a hidden Boolean argument (logical(kind=C_bool),value) is used to indicate whether the argument is present.

Arguments which are assumed-shape, assumed-rank or deferred-rank arrays or, with -fcoarray=lib, allocatable scalar coarrays use an array descriptor.  All other arrays pass the address of the first element of the array.  With -fcoarray=lib, the token and the offset belonging to nonallocatable coarrays dummy arguments are passed as hidden argument along the character length hidden arguments.  The token is an oparque pointer identifying the coarray and the offset is a passed-by-value integer of kind C_PTRDIFF_T, denoting the byte offset between the base address of the coarray and the passed scalar or first element of the passed array.

The arguments are passed in the following order

  * Result variable, when the function result is passed by reference

  * Character length of the function result, if it is a of type CHARACTER and no C binding is used

  * The arguments in the order in which they appear in the Fortran declaration

  * The the present status for optional arguments with value attribute, which are internally passed by value

  * The character length and/or coarray token and offset for the first argument which is a CHARACTER or a nonallocatable coarray dummy argument, followed by the hidden arguments of the next dummy argument of such a type

Coarray Programming
*******************

Type and enum ABI Documentation
===============================

caf_token_t
-----------

Typedef of type void * on the compiler side. Can be any data type on the library side.

caf_register_t
--------------

Indicates which kind of coarray variable should be registered.

typedef enum caf_register_t {
  CAF_REGTYPE_COARRAY_STATIC,
  CAF_REGTYPE_COARRAY_ALLOC,
  CAF_REGTYPE_LOCK_STATIC,
  CAF_REGTYPE_LOCK_ALLOC,
  CAF_REGTYPE_CRITICAL
}
caf_register_t;

Function ABI Documentation
==========================

_gfortran_caf_init --- Initialiation function
---------------------------------------------

Description:
     This function is called at startup of the program before the Fortran main program, if the latter has been compiled with -fcoarray=lib. It takes as arguments the command-line arguments of the program.  It is permitted to pass to NULL pointers as argument; if non-NULL, the library is permitted to modify the arguments.

Syntax:
     void _gfortran_caf_init (int *argc, char ***argv)

Arguments:

     ARGC   intent(inout) An integer pointer with the number of
     arguments passed to the program or NULL.
     ARGV   intent(inout) A pointer to an array of strings with the
     command-line arguments or NULL.

NOTES
     The function is modelled after the initialization function of the Message Passing Interface (MPI) specification.  Due to the way coarray registration works, it might not be the first call to the libaray.  If the main program is not written in Fortran and only a library uses coarrays, it can happen that this function is never called.  Therefore, it is recommended that the library does not rely on the passed arguments and whether the call has been done.

_gfortran_caf_finish --- Finalization function
----------------------------------------------

Description:
     This function is called at the end of the Fortran main program, if it has been compiled with the -fcoarray=lib option.

Syntax:
     void _gfortran_caf_finish (void)

NOTES
     For non-Fortran programs, it is recommended to call the function at the end of the main program.  To ensure that the shutdown is also performed for programs where this function is not explicitly invoked, for instance non-Fortran programs or calls to the system's exit() function, the library can use a destructor function.  Note that programs can also be terminated using the STOP and ERROR STOP statements; those use different library calls.

_gfortran_caf_this_image --- Querying the image number
------------------------------------------------------

Description:
     This function returns the current image number, which is a positive number.

Syntax:
     int _gfortran_caf_this_image (int distance)

Arguments:

     DISTANCE   As specified for the this_image intrinsic
     in TS18508. Shall be a nonnegative number.

NOTES
     If the Fortran intrinsic this_image is invoked without an argument, which is the only permitted form in Fortran 2008, GCC passes 0 as first argument.

_gfortran_caf_num_images --- Querying the maximal number of images
------------------------------------------------------------------

Description:
     This function returns the number of images in the current team, if DISTANCE is 0 or the number of images in the parent team at the specified distance. If failed is -1, the function returns the number of all images at the specified distance; if it is 0, the function returns the number of nonfailed images, and if it is 1, it returns the number of failed images.

Syntax:
     int _gfortran_caf_num_images(int distance, int failed)

Arguments:

     DISTANCE   the distance from this image to the ancestor.
     Shall be positive.
     FAILED   shall be -1, 0, or 1

NOTES
     This function follows TS18508. If the num_image intrinsic has no arguments, the the compiler passes distance=0 and failed=-1 to the function.

_gfortran_caf_register --- Registering coarrays
-----------------------------------------------

Description:
     Allocates memory for a coarray and creates a token to identify the coarray. The function is called for both coarrays with SAVE attribute and using an explicit ALLOCATE statement. If an error occurs and STAT is a NULL pointer, the function shall abort with printing an error message and starting the error termination.  If no error occurs and STAT is present, it shall be set to zero. Otherwise, it shall be set to a positive value and, if not-NULL, ERRMSG shall be set to a string describing the failure. The function shall return a pointer to the requested memory for the local image as a call to malloc would do.

     For CAF_REGTYPE_COARRAY_STATIC and CAF_REGTYPE_COARRAY_ALLOC, the passed size is the byte size requested.  For CAF_REGTYPE_LOCK_STATIC, CAF_REGTYPE_LOCK_ALLOC and CAF_REGTYPE_CRITICAL it is the array size or one for a scalar.

Syntax:
     void *caf_register (size_t size, caf_register_t type, caf_token_t *token, int *stat, char *errmsg, int errmsg_len)

Arguments:

     SIZE   For normal coarrays, the byte size of the coarray to be
     allocated; for lock types, the number of elements.
     TYPE   one of the caf_register_t types.
     TOKEN   intent(out) An opaque pointer identifying the coarray.
     STAT   intent(out) For allocatable coarrays, stores the STAT=;
     may be NULL
     ERRMSG   intent(out) When an error occurs, this will be set to
     an error message; may be NULL
     ERRMSG_LEN   the buffer size of errmsg.

NOTES
     Nonalloatable coarrays have to be registered prior use from remote images. In order to guarantee this, they have to be registered before the main program. This can be achieved by creating constructor functions. That is what GCC does such that also nonallocatable coarrays the memory is allocated and no static memory is used.  The token permits to identify the coarray; to the processor, the token is a nonaliasing pointer. The library can, for instance, store the base address of the coarray in the token, some handle or a more complicated struct.

     For normal coarrays, the returned pointer is used for accesses on the local image. For lock types, the value shall only used for checking the allocation status. Note that for critical blocks, the locking is only required on one image; in the locking statement, the processor shall always pass always an image index of one for critical-block lock variables (CAF_REGTYPE_CRITICAL).

_gfortran_caf_deregister --- Deregistering coarrays
---------------------------------------------------

Description:
     Called to free the memory of a coarray; the processor calls this function for automatic and explicit deallocation.  In case of an error, this function shall fail with an error message, unless the STAT variable is not null.

Syntax:
     void caf_deregister (const caf_token_t *token, int *stat, char *errmsg, int errmsg_len)

Arguments:

     STAT   intent(out) For allocatable coarrays, stores the STAT=;
     may be NULL
     ERRMSG   intent(out) When an error occurs, this will be set
     to an error message; may be NULL
     ERRMSG_LEN   the buffer size of errmsg.

NOTES
     For nonalloatable coarrays this function is never called.  If a cleanup is required, it has to be handled via the finish, stop and error stop functions, and via destructors.

_gfortran_caf_send --- Sending data from a local image to a remote image
------------------------------------------------------------------------

Description:
     Called to send a scalar, an array section or whole array from a local to a remote image identified by the image_index.

Syntax:
     void _gfortran_caf_send (caf_token_t token, size_t offset, int image_index, gfc_descriptor_t *dest, caf_vector_t *dst_vector, gfc_descriptor_t *src, int dst_kind, int src_kind, bool may_require_tmp)

Arguments:

     TOKEN   intent(in)  An opaque pointer identifying the coarray.
     OFFSET   By which amount of bytes the actual data is shifted
     compared to the base address of the coarray.
     IMAGE_INDEX   The ID of the remote image; must be a positive
     number.
     DEST   intent(in) Array descriptor for the remote image for the
     bounds and the size. The base_addr shall not be accessed.
     DST_VECTOR   intent(int)  If not NULL, it contains the vector
     subscript of the destination array; the values are relative to the dimension
     triplet of the dest argument.
     SRC   intent(in) Array descriptor of the local array to be
     transferred to the remote image
     DST_KIND   Kind of the destination argument
     SRC_KIND   Kind of the source argument
     MAY_REQUIRE_TMP   The variable is false it is known at compile
     time that the DEST and SRC either cannot overlap or overlap (fully
     or partially) such that walking SRC and DEST in element wise
     element order (honoring the stride value) will not lead to wrong results.
     Otherwise, the value is true.

NOTES
     It is permitted to have image_id equal the current image; the memory of the send-to and the send-from might (partially) overlap in that case. The implementation has to take care that it handles this case, e.g. using memmove which handles (partially) overlapping memory. If MAY_REQUIRE_TMP is true, the library might additionally create a temporary variable, unless additional checks show that this is not required (e.g. because walking backward is possible or because both arrays are contiguous and memmove takes care of overlap issues).

     Note that the assignment of a scalar to an array is permitted. In addition, the library has to handle numeric-type conversion and for strings, padding and different character kinds.

_gfortran_caf_get --- Getting data from a remote image
------------------------------------------------------

Description:
     Called to get an array section or whole array from a a remote, image identified by the image_index.

Syntax:
     void _gfortran_caf_get_desc (caf_token_t token, size_t offset, int image_index, gfc_descriptor_t *src, caf_vector_t *src_vector, gfc_descriptor_t *dest, int src_kind, int dst_kind, bool may_require_tmp)

Arguments:

     TOKEN   intent(in)  An opaque pointer identifying the coarray.
     OFFSET   By which amount of bytes the actual data is shifted
     compared to the base address of the coarray.
     IMAGE_INDEX   The ID of the remote image; must be a positive
     number.
     DEST   intent(in) Array descriptor of the local array to be
     transferred to the remote image
     SRC   intent(in) Array descriptor for the remote image for the
     bounds and the size. The base_addr shall not be accessed.
     SRC_VECTOR   intent(int)  If not NULL, it contains the vector
     subscript of the destination array; the values are relative to the dimension
     triplet of the dest argument.
     DST_KIND   Kind of the destination argument
     SRC_KIND   Kind of the source argument
     MAY_REQUIRE_TMP   The variable is false it is known at compile
     time that the DEST and SRC either cannot overlap or overlap (fully
     or partially) such that walking SRC and DEST in element wise
     element order (honoring the stride value) will not lead to wrong results.
     Otherwise, the value is true.

NOTES
     It is permitted to have image_id equal the current image; the memory of the send-to and the send-from might (partially) overlap in that case. The implementation has to take care that it handles this case, e.g. using memmove which handles (partially) overlapping memory. If MAY_REQUIRE_TMP is true, the library might additionally create a temporary variable, unless additional checks show that this is not required (e.g. because walking backward is possible or because both arrays are contiguous and memmove takes care of overlap issues).

     Note that the library has to handle numeric-type conversion and for strings, padding and different character kinds.

_gfortran_caf_sendget --- Sending data between remote images
------------------------------------------------------------

Description:
     Called to send a scalar, an array section or whole array from a remote image identified by the src_image_index to a remote image identified by the dst_image_index.

Syntax:
     void _gfortran_caf_sendget (caf_token_t dst_token, size_t dst_offset, int dst_image_index, gfc_descriptor_t *dest, caf_vector_t *dst_vector, caf_token_t src_token, size_t src_offset, int src_image_index, gfc_descriptor_t *src, caf_vector_t *src_vector, int dst_kind, int src_kind, bool may_require_tmp)

Arguments:

     DST_TOKEN   intent(in)  An opaque pointer identifying the
     destination coarray.
     DST_OFFSET    By which amount of bytes the actual data is
     shifted compared to the base address of the destination coarray.
     DST_IMAGE_INDEX   The ID of the destination remote image; must
     be a positive number.
     DEST   intent(in) Array descriptor for the destination
     remote image for the bounds and the size. The base_addr shall not be accessed.
     DST_VECTOR   intent(int)  If not NULL, it contains the vector
     subscript of the destination array; the values are relative to the dimension
     triplet of the dest argument.
     SRC_TOKEN   An opaque pointer identifying the source coarray.
     SRC_OFFSET   By which amount of bytes the actual data is shifted
     compared to the base address of the source coarray.
     SRC_IMAGE_INDEX   The ID of the source remote image; must be a
     positive number.
     SRC   intent(in) Array descriptor of the local array to be
     transferred to the remote image.
     SRC_VECTOR   intent(in) Array descriptor of the local array to
     be transferred to the remote image
     DST_KIND   Kind of the destination argument
     SRC_KIND   Kind of the source argument
     MAY_REQUIRE_TMP   The variable is false it is known at compile
     time that the DEST and SRC either cannot overlap or overlap (fully
     or partially) such that walking SRC and DEST in element wise
     element order (honoring the stride value) will not lead to wrong results.
     Otherwise, the value is true.

NOTES
     It is permitted to have image_ids equal; the memory of the send-to and the send-from might (partially) overlap in that case. The implementation has to take care that it handles this case, e.g. using memmove which handles (partially) overlapping memory. If MAY_REQUIRE_TMP is true, the library might additionally create a temporary variable, unless additional checks show that this is not required (e.g. because walking backward is possible or because both arrays are contiguous and memmove takes care of overlap issues).

     Note that the assignment of a scalar to an array is permitted. In addition, the library has to handle numeric-type conversion and for strings, padding and different character kinds.

_gfortran_caf_lock --- Locking a lock variable
----------------------------------------------

Description:
     Acquire a lock on the given image on a scalar locking variable or for the given array element for an array-valued variable. If the AQUIRED_LOCK is NULL, the function return after having obtained the lock. If it is nonnull, the result is is assigned the value true (one) when the lock could be obtained and false (zero) otherwise.  Locking a lock variable which has already been locked by the same image is an error.

Syntax:
     void _gfortran_caf_lock (caf_token_t token, size_t index, int image_index, int *aquired_lock, int *stat, char *errmsg, int errmsg_len)

Arguments:

     TOKEN   intent(in) An opaque pointer identifying the coarray.
     INDEX   Array index; first array index is 0. For scalars, it is
     always 0.
     IMAGE_INDEX   The ID of the remote image; must be a positive
     number.
     AQUIRED_LOCK   intent(out) If not NULL, it returns whether lock
     could be obtained
     STAT   intent(out) For allocatable coarrays, stores the STAT=;
     may be NULL
     ERRMSG   intent(out) When an error occurs, this will be set to
     an error message; may be NULL
     ERRMSG_LEN   the buffer size of errmsg.

NOTES
     This function is also called for critical blocks; for those, the array index is always zero and the image index is one.  Libraries are permitted to use other images for critical-block locking variables.

_gfortran_caf_lock --- Unlocking a lock variable
------------------------------------------------

Description:
     Release a lock on the given image on a scalar locking variable or for the given array element for an array-valued variable. Unlocking a lock variable which is unlocked or has been locked by a different image is an error.

Syntax:
     void _gfortran_caf_unlock (caf_token_t token, size_t index, int image_index, int *stat, char *errmsg, int errmsg_len)

Arguments:

     TOKEN   intent(in) An opaque pointer identifying the coarray.
     INDEX   Array index; first array index is 0. For scalars, it is
     always 0.
     IMAGE_INDEX   The ID of the remote image; must be a positive
     number.
     STAT   intent(out) For allocatable coarrays, stores the STAT=;
     may be NULL
     ERRMSG   intent(out) When an error occurs, this will be set to
     an error message; may be NULL
     ERRMSG_LEN   the buffer size of errmsg.

NOTES
     This function is also called for critical block; for those, the array index is always zero and the image index is one.  Libraries are permitted to use other images for critical-block locking variables.

_gfortran_caf_sync_all --- All-image barrier
--------------------------------------------

Description:
     Synchronization of all images in the current team; the program only continues on a given image after this function has been called on all images of the current team.  Additionally, it ensures that all pending data transfers of previous segment have completed.

Syntax:
     void _gfortran_caf_sync_all (int *stat, char *errmsg, int errmsg_len)

Arguments:

     STAT   intent(out) Stores the status STAT= and may be NULL.
     ERRMSG   intent(out) When an error occurs, this will be set to
     an error message; may be NULL
     ERRMSG_LEN   the buffer size of errmsg.

_gfortran_caf_sync_images --- Barrier for selected images
---------------------------------------------------------

Description:
     Synchronization between the specified images; the program only continues on a given image after this function has been called on all images specified for that image. Note that one image can wait for all other images in the current team (e.g. via sync images(*)) while those only wait for that specific image.  Additionally, sync images it ensures that all pending data transfers of previous segment have completed.

Syntax:
     void _gfortran_caf_sync_images (int count, int images[], int *stat, char *errmsg, int errmsg_len)

Arguments:

     COUNT   the number of images which are provided in the next
     argument.  For a zero-sized array, the value is zero.  For sync
     images (*), the value is -1.
     IMAGES   intent(in) an array with the images provided by the
     user. If COUNT is zero, a NULL pointer is passed.
     STAT   intent(out) Stores the status STAT= and may be NULL.
     ERRMSG   intent(out) When an error occurs, this will be set to
     an error message; may be NULL
     ERRMSG_LEN   the buffer size of errmsg.

_gfortran_caf_sync_memory --- Wait for completion of segment-memory operations
------------------------------------------------------------------------------

Description:
     Acts as optimization barrier between different segments. It also ensures that all pending memory operations of this image have been completed.

Syntax:
     void _gfortran_caf_sync_memory (int *stat, char *errmsg, int errmsg_len)

Arguments:

     STAT   intent(out) Stores the status STAT= and may be NULL.
     ERRMSG   intent(out) When an error occurs, this will be set to
     an error message; may be NULL
     ERRMSG_LEN   the buffer size of errmsg.

NOTE A simple implementation could be
     __asm__ __volatile__ ("":::"memory") to prevent code movements.

_gfortran_caf_error_stop --- Error termination with exit code
-------------------------------------------------------------

Description:
     Invoked for an ERROR STOP statement which has an integer argument.  The function should terminate the program with the specified exit code.

Syntax:
     void _gfortran_caf_error_stop (int32_t error)

Arguments:

     ERROR   the exit status to be used.

_gfortran_caf_error_stop_str --- Error termination with string
--------------------------------------------------------------

Description:
     Invoked for an ERROR STOP statement which has a string as argument.  The function should terminate the program with a nonzero-exit code.

Syntax:
     void _gfortran_caf_error_stop (const char *string, int32_t len)

Arguments:

     STRING   the error message (not zero terminated)
     LEN   the length of the string

_gfortran_caf_atomic_define --- Atomic variable assignment
----------------------------------------------------------

Description:
     Assign atomically a value to an integer or logical variable.

Syntax:
     void _gfortran_caf_atomic_define (caf_token_t token, size_t offset, int image_index, void *value, int *stat, int type, int kind)

Arguments:

     TOKEN   intent(in) An opaque pointer identifying the coarray.
     OFFSET   By which amount of bytes the actual data is shifted
     compared to the base address of the coarray.
     IMAGE_INDEX   The ID of the remote image; must be a positive
     number.
     VALUE   intent(in) the value to be assigned, passed by reference.
     STAT   intent(out) Stores the status STAT= and may be NULL.
     TYPE   the data type, i.e. BT_INTEGER (1) or
     BT_LOGICAL (2).
     KIND   The kind value (only 4; always int)

_gfortran_caf_atomic_ref --- Atomic variable reference
------------------------------------------------------

Description:
     Reference atomically a value of a kind-4 integer or logical variable.

Syntax:
     void _gfortran_caf_atomic_ref (caf_token_t token, size_t offset, int image_index, void *value, int *stat, int type, int kind)

Arguments:

Arguments:

     TOKEN   intent(in) An opaque pointer identifying the coarray.
     OFFSET   By which amount of bytes the actual data is shifted
     compared to the base address of the coarray.
     IMAGE_INDEX   The ID of the remote image; must be a positive
     number.
     VALUE   intent(out) The variable assigned the atomically
     referenced variable.
     STAT   intent(out) Stores the status STAT= and may be NULL.
     TYPE   the data type, i.e. BT_INTEGER (1) or
     BT_LOGICAL (2).
     KIND   The kind value (only 4; always int)

_gfortran_caf_atomic_cas --- Atomic compare and swap
----------------------------------------------------

Description:
     Atomic compare and swap of a kind-4 integer or logical variable. Assigns atomically the specified value to the atomic variable, if the latter has the value specified by the passed condition value.

Syntax:
     void _gfortran_caf_atomic_cas (caf_token_t token, size_t offset, int image_index, void *old, void *compare, void *new_val, int *stat, int type, int kind)

Arguments:

     TOKEN   intent(in) An opaque pointer identifying the coarray.
     OFFSET   By which amount of bytes the actual data is shifted
     compared to the base address of the coarray.
     IMAGE_INDEX   The ID of the remote image; must be a positive
     number.
     OLD   intent(out) the value which the atomic variable had
     just before the cas operation.
     COMPARE   intent(in) The value used for comparision.
     NEW_VAL   intent(in) The new value for the atomic variable,
     assigned to the atomic variable, if compare equals the value of the
     atomic variable.
     STAT   intent(out) Stores the status STAT= and may be NULL.
     TYPE   the data type, i.e. BT_INTEGER (1) or
     BT_LOGICAL (2).
     KIND   The kind value (only 4; always int)

_gfortran_caf_atomic_op --- Atomic operation
--------------------------------------------

Description:
     Apply an operation atomically to an atomic integer or logical variable. After the operation, OLD contains the value just before the operation, which, respectively, adds (GFC_CAF_ATOMIC_ADD) atomically the value to the atomic integer variable or does a bitwise AND, OR or exclusive OR of the between the atomic variable and VALUE; the result is then stored in the atomic variable.

Syntax:
     void _gfortran_caf_atomic_op (int op, caf_token_t token, size_t offset, int image_index, void *value, void *old, int *stat, int type, int kind)

Arguments:

     OP   the operation to be performed; possible values
     GFC_CAF_ATOMIC_ADD (1), GFC_CAF_ATOMIC_AND (2),
     GFC_CAF_ATOMIC_OR (3), GFC_CAF_ATOMIC_XOR (4).
     TOKEN   intent(in) An opaque pointer identifying the coarray.
     OFFSET   By which amount of bytes the actual data is shifted
     compared to the base address of the coarray.
     IMAGE_INDEX   The ID of the remote image; must be a positive
     number.
     OLD   intent(out) the value which the atomic variable had
     just before the atomic operation.
     VAL   intent(in) The new value for the atomic variable,
     assigned to the atomic variable, if compare equals the value of the
     atomic variable.
     STAT   intent(out) Stores the status STAT= and may be NULL.
     TYPE   the data type, i.e. BT_INTEGER (1) or
     BT_LOGICAL (2).
     KIND   The kind value (only 4; always int)

_gfortran_caf_co_broadcast --- Sending data to all images
---------------------------------------------------------

Description:
     Distribute a value from a given image to all other images in the team. Has to be called collectively.

Syntax:
     void _gfortran_caf_co_broadcast (gfc_descriptor_t *a, int source_image, int *stat, char *errmsg, int errmsg_len)

Arguments:

     A   intent(inout) And array descriptor with the data to be
     breoadcasted (on SOURCE_IMAGE) or to be received (other images).
     SOURCE_IMAGE   The ID of the image from which the data should
     be taken.
     STAT   intent(out) Stores the status STAT= and may be NULL.
     ERRMSG   intent(out) When an error occurs, this will be set to
     an error message; may be NULL
     ERRMSG_LEN   the buffer size of errmsg.

_gfortran_caf_co_max --- Collective maximum reduction
-----------------------------------------------------

Description:
     Calculates the for the each array element of the variable A the maximum value for that element in the current team; if RESULT_IMAGE has the value 0, the result shall be stored on all images, otherwise, only on the specified image. This function operates on numeric values and character strings.

Syntax:
     void _gfortran_caf_co_max (gfc_descriptor_t *a, int result_image, int *stat, char *errmsg, int a_len, int errmsg_len)

Arguments:

     A   intent(inout) And array descriptor with the data to be
     breoadcasted (on SOURCE_IMAGE) or to be received (other images).
     RESULT_IMAGE   The ID of the image to which the reduced
     value should be copied to; if zero, it has to be copied to all images.
     STAT   intent(out) Stores the status STAT= and may be NULL.
     ERRMSG   intent(out) When an error occurs, this will be set to
     an error message; may be NULL
     A_LEN   The string length of argument A.
     ERRMSG_LEN   the buffer size of errmsg.

NOTES
     If RESULT_IMAGE is nonzero, the value on all images except of the specified one become undefined; hence, the library may make use of this.

_gfortran_caf_co_min --- Collective minimum reduction
-----------------------------------------------------

Description:
     Calculates the for the each array element of the variable A the minimum value for that element in the current team; if RESULT_IMAGE has the value 0, the result shall be stored on all images, otherwise, only on the specified image. This function operates on numeric values and character strings.

Syntax:
     void _gfortran_caf_co_min (gfc_descriptor_t *a, int result_image, int *stat, char *errmsg, int a_len, int errmsg_len)

Arguments:

     A   intent(inout) And array descriptor with the data to be
     breoadcasted (on SOURCE_IMAGE) or to be received (other images).
     RESULT_IMAGE   The ID of the image to which the reduced
     value should be copied to; if zero, it has to be copied to all images.
     STAT   intent(out) Stores the status STAT= and may be NULL.
     ERRMSG   intent(out) When an error occurs, this will be set to
     an error message; may be NULL
     A_LEN   The string length of argument A.
     ERRMSG_LEN   the buffer size of errmsg.

NOTES
     If RESULT_IMAGE is nonzero, the value on all images except of the specified one become undefined; hence, the library may make use of this.

_gfortran_caf_co_sum --- Collective summing reduction
-----------------------------------------------------

Description:
     Calculates the for the each array element of the variable A the sum value for that element in the current team; if RESULT_IMAGE has the value 0, the result shall be stored on all images, otherwise, only on the specified image. This function operates on numeric values.

Syntax:
     void _gfortran_caf_co_sum (gfc_descriptor_t *a, int result_image, int *stat, char *errmsg, int errmsg_len)

Arguments:

     A   intent(inout) And array descriptor with the data to be
     breoadcasted (on SOURCE_IMAGE) or to be received (other images).
     RESULT_IMAGE   The ID of the image to which the reduced
     value should be copied to; if zero, it has to be copied to all images.
     STAT   intent(out) Stores the status STAT= and may be NULL.
     ERRMSG   intent(out) When an error occurs, this will be set to
     an error message; may be NULL
     ERRMSG_LEN   the buffer size of errmsg.

NOTES
     If RESULT_IMAGE is nonzero, the value on all images except of the specified one become undefined; hence, the library may make use of this.

_gfortran_caf_co_reduce --- Generic collective reduction
--------------------------------------------------------

Description:
     Calculates the for the each array element of the variable A the reduction value for that element in the current team; if RESULT_IMAGE has the value 0, the result shall be stored on all images, otherwise, only on the specified image. The OPR is a pure function doing a mathematically commutative and associative operation.

     The OPR_FLAGS denote the following; the values are bitwise ored. GFC_CAF_BYREF (1) if the result should be returned by value; GFC_CAF_HIDDENLEN (2) whether the result and argument string lengths shall be specified as hidden argument; GFC_CAF_ARG_VALUE (4) whether the arguments shall be passed by value, GFC_CAF_ARG_DESC (8) whether the arguments shall be passed by descriptor.

Syntax:
     void _gfortran_caf_co_reduce (gfc_descriptor_t *a, void * (*opr) (void *, void *), int opr_flags, int result_image, int *stat, char *errmsg, int a_len, int errmsg_len)

Arguments:

     OPR   Function pointer to the reduction function.
     OPR_FLAGS   Flags regarding the reduction function
     A   intent(inout) And array descriptor with the data to be
     breoadcasted (on SOURCE_IMAGE) or to be received (other images).
     RESULT_IMAGE   The ID of the image to which the reduced
     value should be copied to; if zero, it has to be copied to all images.
     STAT   intent(out) Stores the status STAT= and may be NULL.
     ERRMSG   intent(out) When an error occurs, this will be set to
     an error message; may be NULL
     A_LEN   The string length of argument A.
     ERRMSG_LEN   the buffer size of errmsg.

NOTES
     If RESULT_IMAGE is nonzero, the value on all images except of the specified one become undefined; hence, the library may make use of this. For character arguments, the result is passed as first argument, followed by the result string length, next come the two string arguments, followed by the two hidden arguments. With C binding, there are no hidden arguments and by-reference passing and either only a single character is passed or an array descriptor.

     [file intrinsic.texi not included]

Contributing
************

Free software is only possible if people contribute to efforts to create it. We're always in need of more people helping out with ideas and comments, writing documentation and contributing code.

If you want to contribute to GNU Fortran, have a look at the long lists of projects you can take on. Some of these projects are small, some of them are large; some are completely orthogonal to the rest of what is happening on GNU Fortran, but others are ``mainstream'' projects in need of enthusiastic hackers. All of these projects are important! We will eventually get around to the things here, but they are also things doable by someone who is willing and able.

Contributors to GNU Fortran
===========================

Most of the parser was hand-crafted by Andy Vaught, who is also the initiator of the whole project.  Thanks Andy! Most of the interface with GCC was written by Paul Brook.

The following individuals have contributed code and/or ideas and significant help to the GNU Fortran project (in alphabetical order):

  - Janne Blomqvist

  - Steven Bosscher

  - Paul Brook

  - Tobias Burnus

  - François-Xavier Coudert

  - Bud Davis

  - Jerry DeLisle

  - Erik Edelmann

  - Bernhard Fischer

  - Daniel Franke

  - Richard Guenther

  - Richard Henderson

  - Katherine Holcomb

  - Jakub Jelinek

  - Niels Kristian Bech Jensen

  - Steven Johnson

  - Steven G. Kargl

  - Thomas Koenig

  - Asher Langton

  - H. J. Lu

  - Toon Moene

  - Brooks Moses

  - Andrew Pinski

  - Tim Prince

  - Christopher D. Rickett

  - Richard Sandiford

  - Tobias Schlüter

  - Roger Sayle

  - Paul Thomas

  - Andy Vaught

  - Feng Wang

  - Janus Weil

  - Daniel Kraft

The following people have contributed bug reports, smaller or larger patches, and much needed feedback and encouragement for the GNU Fortran project:

  - Bill Clodius

  - Dominique d'Humières

  - Kate Hedstrom

  - Erik Schnetter

  - Joost VandeVondele

Many other individuals have helped debug, test and improve the GNU Fortran compiler over the past few years, and we welcome you to do the same! If you already have done so, and you would like to see your name listed in the list above, please contact us.

Projects
========

Help build the test suite
     Solicit more code for donation to the test suite: the more extensive the testsuite, the smaller the risk of breaking things in the future! We can keep code private on request.

Bug hunting/squishing
     Find bugs and write more test cases! Test cases are especially very welcome, because it allows us to concentrate on fixing bugs instead of isolating them.  Going through the bugzilla database at https://gcc.gnu.org/bugzilla/ to reduce testcases posted there and add more information (for example, for which version does the testcase work, for which versions does it fail?) is also very helpful.

Proposed Extensions
===================

Here's a list of proposed extensions for the GNU Fortran compiler, in no particular order.  Most of these are necessary to be fully compatible with existing Fortran compilers, but they are not part of the official J3 Fortran 95 standard.

Compiler extensions:
--------------------

  * User-specified alignment rules for structures.

  * Automatically extend single precision constants to double.

  * Compile code that conserves memory by dynamically allocating common and module storage either on stack or heap.

  * Compile flag to generate code for array conformance checking (suggest -CC).

  * User control of symbol names (underscores, etc).

  * Compile setting for maximum size of stack frame size before spilling parts to static or heap.

  * Flag to force local variables into static space.

  * Flag to force local variables onto stack.

Environment Options
-------------------

  * Pluggable library modules for random numbers, linear algebra. LA should use BLAS calling conventions.

  * Environment variables controlling actions on arithmetic exceptions like overflow, underflow, precision loss---Generate NaN, abort, default. action.

  * Set precision for fp units that support it (i387).

  * Variable for setting fp rounding mode.

  * Variable to fill uninitialized variables with a user-defined bit pattern.

  * Environment variable controlling filename that is opened for that unit number.

  * Environment variable to clear/trash memory being freed.

  * Environment variable to control tracing of allocations and frees.

  * Environment variable to display allocated memory at normal program end.

  * Environment variable for filename for * IO-unit.

  * Environment variable for temporary file directory.

  * Environment variable forcing standard output to be line buffered (Unix).

     [file gpl_v3.texi not included]

     [file fdl.texi not included]

     [file funding.texi not included]

Option Index
************

gfortran's command line options are indexed here without any initial - or --.  Where an option has both positive and negative forms (such as -foption and -fno-option), relevant entries in the manual are indexed under the most appropriate form; it may sometimes be useful to look up both forms.