Reverting merge from trunk
[official-gcc.git] / gcc / fortran / gfortran.texi
blob292569b537622aaddf6b30d8ac3e2ca84ea5c148
1 \input texinfo  @c -*-texinfo-*-
2 @c %**start of header
3 @setfilename gfortran.info
4 @set copyrights-gfortran 1999-2013
6 @include gcc-common.texi
8 @settitle The GNU Fortran Compiler
10 @c Create a separate index for command line options
11 @defcodeindex op
12 @c Merge the standard indexes into a single one.
13 @syncodeindex fn cp
14 @syncodeindex vr cp
15 @syncodeindex ky cp
16 @syncodeindex pg cp
17 @syncodeindex tp cp
19 @c TODO: The following "Part" definitions are included here temporarily
20 @c until they are incorporated into the official Texinfo distribution.
21 @c They borrow heavily from Texinfo's \unnchapentry definitions.
23 @tex
24 \gdef\part#1#2{%
25   \pchapsepmacro
26   \gdef\thischapter{}
27   \begingroup
28     \vglue\titlepagetopglue
29     \titlefonts \rm
30     \leftline{Part #1:@* #2}
31     \vskip4pt \hrule height 4pt width \hsize \vskip4pt
32   \endgroup
33   \writetocentry{part}{#2}{#1}
35 \gdef\blankpart{%
36   \writetocentry{blankpart}{}{}
38 % Part TOC-entry definition for summary contents.
39 \gdef\dosmallpartentry#1#2#3#4{%
40   \vskip .5\baselineskip plus.2\baselineskip
41   \begingroup
42     \let\rm=\bf \rm
43     \tocentry{Part #2: #1}{\doshortpageno\bgroup#4\egroup}
44   \endgroup
46 \gdef\dosmallblankpartentry#1#2#3#4{%
47   \vskip .5\baselineskip plus.2\baselineskip
49 % Part TOC-entry definition for regular contents.  This has to be
50 % equated to an existing entry to not cause problems when the PDF
51 % outline is created.
52 \gdef\dopartentry#1#2#3#4{%
53   \unnchapentry{Part #2: #1}{}{#3}{#4}
55 \gdef\doblankpartentry#1#2#3#4{}
56 @end tex
58 @c %**end of header
60 @c Use with @@smallbook.
62 @c %** start of document
64 @c Cause even numbered pages to be printed on the left hand side of
65 @c the page and odd numbered pages to be printed on the right hand
66 @c side of the page.  Using this, you can print on both sides of a
67 @c sheet of paper and have the text on the same part of the sheet.
69 @c The text on right hand pages is pushed towards the right hand
70 @c margin and the text on left hand pages is pushed toward the left
71 @c hand margin.
72 @c (To provide the reverse effect, set bindingoffset to -0.75in.)
74 @c @tex
75 @c \global\bindingoffset=0.75in
76 @c \global\normaloffset =0.75in
77 @c @end tex
79 @copying
80 Copyright @copyright{} @value{copyrights-gfortran} Free Software Foundation, Inc.
82 Permission is granted to copy, distribute and/or modify this document
83 under the terms of the GNU Free Documentation License, Version 1.3 or
84 any later version published by the Free Software Foundation; with the
85 Invariant Sections being ``Funding Free Software'', the Front-Cover
86 Texts being (a) (see below), and with the Back-Cover Texts being (b)
87 (see below).  A copy of the license is included in the section entitled
88 ``GNU Free Documentation License''.
90 (a) The FSF's Front-Cover Text is:
92      A GNU Manual
94 (b) The FSF's Back-Cover Text is:
96      You have freedom to copy and modify this GNU Manual, like GNU
97      software.  Copies published by the Free Software Foundation raise
98      funds for GNU development.
99 @end copying
101 @ifinfo
102 @dircategory Software development
103 @direntry
104 * gfortran: (gfortran).                  The GNU Fortran Compiler.
105 @end direntry
106 This file documents the use and the internals of
107 the GNU Fortran compiler, (@command{gfortran}).
109 Published by the Free Software Foundation
110 51 Franklin Street, Fifth Floor
111 Boston, MA 02110-1301 USA
113 @insertcopying
114 @end ifinfo
117 @setchapternewpage odd
118 @titlepage
119 @title Using GNU Fortran
120 @versionsubtitle
121 @author The @t{gfortran} team
122 @page
123 @vskip 0pt plus 1filll
124 Published by the Free Software Foundation@*
125 51 Franklin Street, Fifth Floor@*
126 Boston, MA 02110-1301, USA@*
127 @c Last printed ??ber, 19??.@*
128 @c Printed copies are available for $? each.@*
129 @c ISBN ???
130 @sp 1
131 @insertcopying
132 @end titlepage
134 @c TODO: The following "Part" definitions are included here temporarily
135 @c until they are incorporated into the official Texinfo distribution.
137 @tex
138 \global\let\partentry=\dosmallpartentry
139 \global\let\blankpartentry=\dosmallblankpartentry
140 @end tex
141 @summarycontents
143 @tex
144 \global\let\partentry=\dopartentry
145 \global\let\blankpartentry=\doblankpartentry
146 @end tex
147 @contents
149 @page
151 @c ---------------------------------------------------------------------
152 @c TexInfo table of contents.
153 @c ---------------------------------------------------------------------
155 @ifnottex
156 @node Top
157 @top Introduction
158 @cindex Introduction
160 This manual documents the use of @command{gfortran}, 
161 the GNU Fortran compiler.  You can find in this manual how to invoke
162 @command{gfortran}, as well as its features and incompatibilities.
164 @ifset DEVELOPMENT
165 @emph{Warning:} This document, and the compiler it describes, are still
166 under development.  While efforts are made to keep it up-to-date, it might
167 not accurately reflect the status of the most recent GNU Fortran compiler.
168 @end ifset
170 @comment
171 @comment  When you add a new menu item, please keep the right hand
172 @comment  aligned to the same column.  Do not use tabs.  This provides
173 @comment  better formatting.
174 @comment
175 @menu
176 * Introduction::
178 Part I: Invoking GNU Fortran
179 * Invoking GNU Fortran:: Command options supported by @command{gfortran}.
180 * Runtime::              Influencing runtime behavior with environment variables.
182 Part II: Language Reference
183 * Fortran 2003 and 2008 status::  Fortran 2003 and 2008 features supported by GNU Fortran.
184 * Compiler Characteristics::      User-visible implementation details.
185 * Extensions::                    Language extensions implemented by GNU Fortran.
186 * Mixed-Language Programming::    Interoperability with C
187 * Intrinsic Procedures:: Intrinsic procedures supported by GNU Fortran.
188 * Intrinsic Modules::    Intrinsic modules supported by GNU Fortran.
190 * Contributing::         How you can help.
191 * Copying::              GNU General Public License says
192                          how you can copy and share GNU Fortran.
193 * GNU Free Documentation License::
194                          How you can copy and share this manual.
195 * Funding::              How to help assure continued work for free software.
196 * Option Index::         Index of command line options
197 * Keyword Index::        Index of concepts
198 @end menu
199 @end ifnottex
201 @c ---------------------------------------------------------------------
202 @c Introduction
203 @c ---------------------------------------------------------------------
205 @node Introduction
206 @chapter Introduction
208 @c The following duplicates the text on the TexInfo table of contents.
209 @iftex
210 This manual documents the use of @command{gfortran}, the GNU Fortran
211 compiler.  You can find in this manual how to invoke @command{gfortran},
212 as well as its features and incompatibilities.
214 @ifset DEVELOPMENT
215 @emph{Warning:} This document, and the compiler it describes, are still
216 under development.  While efforts are made to keep it up-to-date, it
217 might not accurately reflect the status of the most recent GNU Fortran
218 compiler.
219 @end ifset
220 @end iftex
222 The GNU Fortran compiler front end was
223 designed initially as a free replacement for,
224 or alternative to, the Unix @command{f95} command;
225 @command{gfortran} is the command you will use to invoke the compiler.
227 @menu
228 * About GNU Fortran::    What you should know about the GNU Fortran compiler.
229 * GNU Fortran and GCC::  You can compile Fortran, C, or other programs.
230 * Preprocessing and conditional compilation:: The Fortran preprocessor
231 * GNU Fortran and G77::  Why we chose to start from scratch.
232 * Project Status::       Status of GNU Fortran, roadmap, proposed extensions.
233 * Standards::            Standards supported by GNU Fortran.
234 @end menu
237 @c ---------------------------------------------------------------------
238 @c About GNU Fortran
239 @c ---------------------------------------------------------------------
241 @node About GNU Fortran
242 @section About GNU Fortran
244 The GNU Fortran compiler supports the Fortran 77, 90 and 95 standards
245 completely, parts of the Fortran 2003 and Fortran 2008 standards, and
246 several vendor extensions.  The development goal is to provide the
247 following features:
249 @itemize @bullet
250 @item
251 Read a user's program,
252 stored in a file and containing instructions written
253 in Fortran 77, Fortran 90, Fortran 95, Fortran 2003 or Fortran 2008.
254 This file contains @dfn{source code}.
256 @item
257 Translate the user's program into instructions a computer
258 can carry out more quickly than it takes to translate the
259 instructions in the first
260 place.  The result after compilation of a program is
261 @dfn{machine code},
262 code designed to be efficiently translated and processed
263 by a machine such as your computer.
264 Humans usually are not as good writing machine code
265 as they are at writing Fortran (or C++, Ada, or Java),
266 because it is easy to make tiny mistakes writing machine code.
268 @item
269 Provide the user with information about the reasons why
270 the compiler is unable to create a binary from the source code.
271 Usually this will be the case if the source code is flawed.
272 The Fortran 90 standard requires that the compiler can point out
273 mistakes to the user.
274 An incorrect usage of the language causes an @dfn{error message}.
276 The compiler will also attempt to diagnose cases where the
277 user's program contains a correct usage of the language,
278 but instructs the computer to do something questionable.
279 This kind of diagnostics message is called a @dfn{warning message}.
281 @item
282 Provide optional information about the translation passes
283 from the source code to machine code.
284 This can help a user of the compiler to find the cause of
285 certain bugs which may not be obvious in the source code,
286 but may be more easily found at a lower level compiler output.
287 It also helps developers to find bugs in the compiler itself.
289 @item
290 Provide information in the generated machine code that can
291 make it easier to find bugs in the program (using a debugging tool,
292 called a @dfn{debugger}, such as the GNU Debugger @command{gdb}). 
294 @item
295 Locate and gather machine code already generated to
296 perform actions requested by statements in the user's program.
297 This machine code is organized into @dfn{modules} and is located
298 and @dfn{linked} to the user program. 
299 @end itemize
301 The GNU Fortran compiler consists of several components:
303 @itemize @bullet
304 @item
305 A version of the @command{gcc} command
306 (which also might be installed as the system's @command{cc} command)
307 that also understands and accepts Fortran source code.
308 The @command{gcc} command is the @dfn{driver} program for
309 all the languages in the GNU Compiler Collection (GCC);
310 With @command{gcc},
311 you can compile the source code of any language for
312 which a front end is available in GCC.
314 @item
315 The @command{gfortran} command itself,
316 which also might be installed as the
317 system's @command{f95} command.
318 @command{gfortran} is just another driver program,
319 but specifically for the Fortran compiler only.
320 The difference with @command{gcc} is that @command{gfortran}
321 will automatically link the correct libraries to your program.
323 @item
324 A collection of run-time libraries.
325 These libraries contain the machine code needed to support
326 capabilities of the Fortran language that are not directly
327 provided by the machine code generated by the
328 @command{gfortran} compilation phase,
329 such as intrinsic functions and subroutines,
330 and routines for interaction with files and the operating system.
331 @c and mechanisms to spawn,
332 @c unleash and pause threads in parallelized code.
334 @item
335 The Fortran compiler itself, (@command{f951}).
336 This is the GNU Fortran parser and code generator,
337 linked to and interfaced with the GCC backend library.
338 @command{f951} ``translates'' the source code to
339 assembler code.  You would typically not use this
340 program directly;
341 instead, the @command{gcc} or @command{gfortran} driver
342 programs will call it for you.
343 @end itemize
346 @c ---------------------------------------------------------------------
347 @c GNU Fortran and GCC
348 @c ---------------------------------------------------------------------
350 @node GNU Fortran and GCC
351 @section GNU Fortran and GCC
352 @cindex GNU Compiler Collection
353 @cindex GCC
355 GNU Fortran is a part of GCC, the @dfn{GNU Compiler Collection}.  GCC
356 consists of a collection of front ends for various languages, which
357 translate the source code into a language-independent form called
358 @dfn{GENERIC}.  This is then processed by a common middle end which
359 provides optimization, and then passed to one of a collection of back
360 ends which generate code for different computer architectures and
361 operating systems.
363 Functionally, this is implemented with a driver program (@command{gcc})
364 which provides the command-line interface for the compiler.  It calls
365 the relevant compiler front-end program (e.g., @command{f951} for
366 Fortran) for each file in the source code, and then calls the assembler
367 and linker as appropriate to produce the compiled output.  In a copy of
368 GCC which has been compiled with Fortran language support enabled,
369 @command{gcc} will recognize files with @file{.f}, @file{.for}, @file{.ftn},
370 @file{.f90}, @file{.f95}, @file{.f03} and @file{.f08} extensions as
371 Fortran source code, and compile it accordingly.  A @command{gfortran}
372 driver program is also provided, which is identical to @command{gcc}
373 except that it automatically links the Fortran runtime libraries into the
374 compiled program.
376 Source files with @file{.f}, @file{.for}, @file{.fpp}, @file{.ftn}, @file{.F},
377 @file{.FOR}, @file{.FPP}, and @file{.FTN} extensions are treated as fixed form.
378 Source files with @file{.f90}, @file{.f95}, @file{.f03}, @file{.f08},
379 @file{.F90}, @file{.F95}, @file{.F03} and @file{.F08} extensions are
380 treated as free form.  The capitalized versions of either form are run
381 through preprocessing.  Source files with the lower case @file{.fpp}
382 extension are also run through preprocessing.
384 This manual specifically documents the Fortran front end, which handles
385 the programming language's syntax and semantics.  The aspects of GCC
386 which relate to the optimization passes and the back-end code generation
387 are documented in the GCC manual; see 
388 @ref{Top,,Introduction,gcc,Using the GNU Compiler Collection (GCC)}.
389 The two manuals together provide a complete reference for the GNU
390 Fortran compiler.
393 @c ---------------------------------------------------------------------
394 @c Preprocessing and conditional compilation
395 @c ---------------------------------------------------------------------
397 @node Preprocessing and conditional compilation
398 @section Preprocessing and conditional compilation
399 @cindex CPP
400 @cindex FPP
401 @cindex Conditional compilation
402 @cindex Preprocessing
403 @cindex preprocessor, include file handling
405 Many Fortran compilers including GNU Fortran allow passing the source code
406 through a C preprocessor (CPP; sometimes also called the Fortran preprocessor,
407 FPP) to allow for conditional compilation.  In the case of GNU Fortran,
408 this is the GNU C Preprocessor in the traditional mode.  On systems with
409 case-preserving file names, the preprocessor is automatically invoked if the
410 filename extension is @file{.F}, @file{.FOR}, @file{.FTN}, @file{.fpp},
411 @file{.FPP}, @file{.F90}, @file{.F95}, @file{.F03} or @file{.F08}.  To manually
412 invoke the preprocessor on any file, use @option{-cpp}, to disable
413 preprocessing on files where the preprocessor is run automatically, use
414 @option{-nocpp}.
416 If a preprocessed file includes another file with the Fortran @code{INCLUDE}
417 statement, the included file is not preprocessed.  To preprocess included
418 files, use the equivalent preprocessor statement @code{#include}.
420 If GNU Fortran invokes the preprocessor, @code{__GFORTRAN__}
421 is defined and @code{__GNUC__}, @code{__GNUC_MINOR__} and
422 @code{__GNUC_PATCHLEVEL__} can be used to determine the version of the
423 compiler.  See @ref{Top,,Overview,cpp,The C Preprocessor} for details.
425 While CPP is the de-facto standard for preprocessing Fortran code,
426 Part 3 of the Fortran 95 standard (ISO/IEC 1539-3:1998) defines
427 Conditional Compilation, which is not widely used and not directly
428 supported by the GNU Fortran compiler.  You can use the program coco
429 to preprocess such files (@uref{http://www.daniellnagle.com/coco.html}).
432 @c ---------------------------------------------------------------------
433 @c GNU Fortran and G77
434 @c ---------------------------------------------------------------------
436 @node GNU Fortran and G77
437 @section GNU Fortran and G77
438 @cindex Fortran 77
439 @cindex @command{g77}
441 The GNU Fortran compiler is the successor to @command{g77}, the Fortran 
442 77 front end included in GCC prior to version 4.  It is an entirely new 
443 program that has been designed to provide Fortran 95 support and 
444 extensibility for future Fortran language standards, as well as providing 
445 backwards compatibility for Fortran 77 and nearly all of the GNU language 
446 extensions supported by @command{g77}.
449 @c ---------------------------------------------------------------------
450 @c Project Status
451 @c ---------------------------------------------------------------------
453 @node Project Status
454 @section Project Status
456 @quotation
457 As soon as @command{gfortran} can parse all of the statements correctly,
458 it will be in the ``larva'' state.
459 When we generate code, the ``puppa'' state.
460 When @command{gfortran} is done,
461 we'll see if it will be a beautiful butterfly,
462 or just a big bug....
464 --Andy Vaught, April 2000
465 @end quotation
467 The start of the GNU Fortran 95 project was announced on
468 the GCC homepage in March 18, 2000
469 (even though Andy had already been working on it for a while,
470 of course).
472 The GNU Fortran compiler is able to compile nearly all
473 standard-compliant Fortran 95, Fortran 90, and Fortran 77 programs,
474 including a number of standard and non-standard extensions, and can be
475 used on real-world programs.  In particular, the supported extensions
476 include OpenMP, Cray-style pointers, and several Fortran 2003 and Fortran
477 2008 features, including TR 15581.  However, it is still under
478 development and has a few remaining rough edges.
480 At present, the GNU Fortran compiler passes the
481 @uref{http://www.fortran-2000.com/ArnaudRecipes/fcvs21_f95.html, 
482 NIST Fortran 77 Test Suite}, and produces acceptable results on the
483 @uref{http://www.netlib.org/lapack/faq.html#1.21, LAPACK Test Suite}.
484 It also provides respectable performance on 
485 the @uref{http://www.polyhedron.com/pb05.html, Polyhedron Fortran
486 compiler benchmarks} and the
487 @uref{http://www.llnl.gov/asci_benchmarks/asci/limited/lfk/README.html,
488 Livermore Fortran Kernels test}.  It has been used to compile a number of
489 large real-world programs, including
490 @uref{http://mysite.verizon.net/serveall/moene.pdf, the HIRLAM
491 weather-forecasting code} and
492 @uref{http://www.theochem.uwa.edu.au/tonto/, the Tonto quantum 
493 chemistry package}; see @url{http://gcc.gnu.org/@/wiki/@/GfortranApps} for an
494 extended list.
496 Among other things, the GNU Fortran compiler is intended as a replacement
497 for G77.  At this point, nearly all programs that could be compiled with
498 G77 can be compiled with GNU Fortran, although there are a few minor known
499 regressions.
501 The primary work remaining to be done on GNU Fortran falls into three
502 categories: bug fixing (primarily regarding the treatment of invalid code
503 and providing useful error messages), improving the compiler optimizations
504 and the performance of compiled code, and extending the compiler to support
505 future standards---in particular, Fortran 2003 and Fortran 2008.
508 @c ---------------------------------------------------------------------
509 @c Standards
510 @c ---------------------------------------------------------------------
512 @node Standards
513 @section Standards
514 @cindex Standards
516 @menu
517 * Varying Length Character Strings::
518 @end menu
520 The GNU Fortran compiler implements
521 ISO/IEC 1539:1997 (Fortran 95).  As such, it can also compile essentially all
522 standard-compliant Fortran 90 and Fortran 77 programs.   It also supports
523 the ISO/IEC TR-15581 enhancements to allocatable arrays.
525 GNU Fortran also have a partial support for ISO/IEC 1539-1:2004 (Fortran
526 2003), ISO/IEC 1539-1:2010 (Fortran 2008), the Technical Specification
527 @code{Further Interoperability of Fortran with C} (ISO/IEC TS 29113:2012).
528 Full support of those standards and future Fortran standards is planned.
529 The current status of the support is can be found in the
530 @ref{Fortran 2003 status}, @ref{Fortran 2008 status} and
531 @ref{TS 29113 status} sections of the documentation.
533 Additionally, the GNU Fortran compilers supports the OpenMP specification
534 (version 3.1, @url{http://openmp.org/@/wp/@/openmp-specifications/}).
536 @node Varying Length Character Strings
537 @subsection Varying Length Character Strings
538 @cindex Varying length character strings
539 @cindex Varying length strings
540 @cindex strings, varying length
542 The Fortran 95 standard specifies in Part 2 (ISO/IEC 1539-2:2000)
543 varying length character strings.  While GNU Fortran currently does not
544 support such strings directly, there exist two Fortran implementations
545 for them, which work with GNU Fortran.  They can be found at
546 @uref{http://www.fortran.com/@/iso_varying_string.f95} and at
547 @uref{ftp://ftp.nag.co.uk/@/sc22wg5/@/ISO_VARYING_STRING/}.
549 Deferred-length character strings of Fortran 2003 supports part of
550 the features of @code{ISO_VARYING_STRING} and should be considered as
551 replacement. (Namely, allocatable or pointers of the type
552 @code{character(len=:)}.)
555 @c =====================================================================
556 @c PART I: INVOCATION REFERENCE
557 @c =====================================================================
559 @tex
560 \part{I}{Invoking GNU Fortran}
561 @end tex
563 @c ---------------------------------------------------------------------
564 @c Compiler Options
565 @c ---------------------------------------------------------------------
567 @include invoke.texi
570 @c ---------------------------------------------------------------------
571 @c Runtime
572 @c ---------------------------------------------------------------------
574 @node Runtime
575 @chapter Runtime:  Influencing runtime behavior with environment variables
576 @cindex environment variable
578 The behavior of the @command{gfortran} can be influenced by
579 environment variables.
581 Malformed environment variables are silently ignored.
583 @menu
584 * TMPDIR:: Directory for scratch files
585 * GFORTRAN_STDIN_UNIT:: Unit number for standard input
586 * GFORTRAN_STDOUT_UNIT:: Unit number for standard output
587 * GFORTRAN_STDERR_UNIT:: Unit number for standard error
588 * GFORTRAN_UNBUFFERED_ALL:: Do not buffer I/O for all units.
589 * GFORTRAN_UNBUFFERED_PRECONNECTED:: Do not buffer I/O for preconnected units.
590 * GFORTRAN_SHOW_LOCUS::  Show location for runtime errors
591 * GFORTRAN_OPTIONAL_PLUS:: Print leading + where permitted
592 * GFORTRAN_DEFAULT_RECL:: Default record length for new files
593 * GFORTRAN_LIST_SEPARATOR::  Separator for list output
594 * GFORTRAN_CONVERT_UNIT::  Set endianness for unformatted I/O
595 * GFORTRAN_ERROR_BACKTRACE:: Show backtrace on run-time errors
596 @end menu
598 @node TMPDIR
599 @section @env{TMPDIR}---Directory for scratch files
601 When opening a file with @code{STATUS='SCRATCH'}, GNU Fortran tries to
602 create the file in one of the potential directories by testing each
603 directory in the order below.
605 @enumerate
606 @item
607 The environment variable @env{TMPDIR}, if it exists.
609 @item
610 On the MinGW target, the directory returned by the @code{GetTempPath}
611 function. Alternatively, on the Cygwin target, the @env{TMP} and
612 @env{TEMP} environment variables, if they exist, in that order.
614 @item
615 The @code{P_tmpdir} macro if it is defined, otherwise the directory
616 @file{/tmp}.
617 @end enumerate
619 @node GFORTRAN_STDIN_UNIT
620 @section @env{GFORTRAN_STDIN_UNIT}---Unit number for standard input
622 This environment variable can be used to select the unit number
623 preconnected to standard input.  This must be a positive integer.
624 The default value is 5.
626 @node GFORTRAN_STDOUT_UNIT
627 @section @env{GFORTRAN_STDOUT_UNIT}---Unit number for standard output
629 This environment variable can be used to select the unit number
630 preconnected to standard output.  This must be a positive integer.
631 The default value is 6.
633 @node GFORTRAN_STDERR_UNIT
634 @section @env{GFORTRAN_STDERR_UNIT}---Unit number for standard error
636 This environment variable can be used to select the unit number
637 preconnected to standard error.  This must be a positive integer.
638 The default value is 0.
640 @node GFORTRAN_UNBUFFERED_ALL
641 @section @env{GFORTRAN_UNBUFFERED_ALL}---Do not buffer I/O on all units
643 This environment variable controls whether all I/O is unbuffered.  If
644 the first letter is @samp{y}, @samp{Y} or @samp{1}, all I/O is
645 unbuffered.  This will slow down small sequential reads and writes.  If
646 the first letter is @samp{n}, @samp{N} or @samp{0}, I/O is buffered.
647 This is the default.
649 @node GFORTRAN_UNBUFFERED_PRECONNECTED
650 @section @env{GFORTRAN_UNBUFFERED_PRECONNECTED}---Do not buffer I/O on preconnected units
652 The environment variable named @env{GFORTRAN_UNBUFFERED_PRECONNECTED} controls
653 whether I/O on a preconnected unit (i.e.@: STDOUT or STDERR) is unbuffered.  If 
654 the first letter is @samp{y}, @samp{Y} or @samp{1}, I/O is unbuffered.  This
655 will slow down small sequential reads and writes.  If the first letter
656 is @samp{n}, @samp{N} or @samp{0}, I/O is buffered.  This is the default.
658 @node GFORTRAN_SHOW_LOCUS
659 @section @env{GFORTRAN_SHOW_LOCUS}---Show location for runtime errors
661 If the first letter is @samp{y}, @samp{Y} or @samp{1}, filename and
662 line numbers for runtime errors are printed.  If the first letter is
663 @samp{n}, @samp{N} or @samp{0}, do not print filename and line numbers
664 for runtime errors.  The default is to print the location.
666 @node GFORTRAN_OPTIONAL_PLUS
667 @section @env{GFORTRAN_OPTIONAL_PLUS}---Print leading + where permitted
669 If the first letter is @samp{y}, @samp{Y} or @samp{1},
670 a plus sign is printed
671 where permitted by the Fortran standard.  If the first letter
672 is @samp{n}, @samp{N} or @samp{0}, a plus sign is not printed
673 in most cases.  Default is not to print plus signs.
675 @node GFORTRAN_DEFAULT_RECL
676 @section @env{GFORTRAN_DEFAULT_RECL}---Default record length for new files
678 This environment variable specifies the default record length, in
679 bytes, for files which are opened without a @code{RECL} tag in the
680 @code{OPEN} statement.  This must be a positive integer.  The
681 default value is 1073741824 bytes (1 GB).
683 @node GFORTRAN_LIST_SEPARATOR
684 @section @env{GFORTRAN_LIST_SEPARATOR}---Separator for list output
686 This environment variable specifies the separator when writing
687 list-directed output.  It may contain any number of spaces and
688 at most one comma.  If you specify this on the command line,
689 be sure to quote spaces, as in
690 @smallexample
691 $ GFORTRAN_LIST_SEPARATOR='  ,  ' ./a.out
692 @end smallexample
693 when @command{a.out} is the compiled Fortran program that you want to run.
694 Default is a single space.
696 @node GFORTRAN_CONVERT_UNIT
697 @section @env{GFORTRAN_CONVERT_UNIT}---Set endianness for unformatted I/O
699 By setting the @env{GFORTRAN_CONVERT_UNIT} variable, it is possible
700 to change the representation of data for unformatted files.
701 The syntax for the @env{GFORTRAN_CONVERT_UNIT} variable is:
702 @smallexample
703 GFORTRAN_CONVERT_UNIT: mode | mode ';' exception | exception ;
704 mode: 'native' | 'swap' | 'big_endian' | 'little_endian' ;
705 exception: mode ':' unit_list | unit_list ;
706 unit_list: unit_spec | unit_list unit_spec ;
707 unit_spec: INTEGER | INTEGER '-' INTEGER ;
708 @end smallexample
709 The variable consists of an optional default mode, followed by
710 a list of optional exceptions, which are separated by semicolons
711 from the preceding default and each other.  Each exception consists
712 of a format and a comma-separated list of units.  Valid values for
713 the modes are the same as for the @code{CONVERT} specifier:
715 @itemize @w{}
716 @item @code{NATIVE} Use the native format.  This is the default.
717 @item @code{SWAP} Swap between little- and big-endian.
718 @item @code{LITTLE_ENDIAN} Use the little-endian format
719 for unformatted files.
720 @item @code{BIG_ENDIAN} Use the big-endian format for unformatted files.
721 @end itemize
722 A missing mode for an exception is taken to mean @code{BIG_ENDIAN}.
723 Examples of values for @env{GFORTRAN_CONVERT_UNIT} are:
724 @itemize @w{}
725 @item @code{'big_endian'}  Do all unformatted I/O in big_endian mode.
726 @item @code{'little_endian;native:10-20,25'}  Do all unformatted I/O 
727 in little_endian mode, except for units 10 to 20 and 25, which are in
728 native format.
729 @item @code{'10-20'}  Units 10 to 20 are big-endian, the rest is native.
730 @end itemize
732 Setting the environment variables should be done on the command
733 line or via the @command{export}
734 command for @command{sh}-compatible shells and via @command{setenv}
735 for @command{csh}-compatible shells.
737 Example for @command{sh}:
738 @smallexample
739 $ gfortran foo.f90
740 $ GFORTRAN_CONVERT_UNIT='big_endian;native:10-20' ./a.out
741 @end smallexample
743 Example code for @command{csh}:
744 @smallexample
745 % gfortran foo.f90
746 % setenv GFORTRAN_CONVERT_UNIT 'big_endian;native:10-20'
747 % ./a.out
748 @end smallexample
750 Using anything but the native representation for unformatted data
751 carries a significant speed overhead.  If speed in this area matters
752 to you, it is best if you use this only for data that needs to be
753 portable.
755 @xref{CONVERT specifier}, for an alternative way to specify the
756 data representation for unformatted files.  @xref{Runtime Options}, for
757 setting a default data representation for the whole program.  The
758 @code{CONVERT} specifier overrides the @option{-fconvert} compile options.
760 @emph{Note that the values specified via the GFORTRAN_CONVERT_UNIT
761 environment variable will override the CONVERT specifier in the
762 open statement}.  This is to give control over data formats to
763 users who do not have the source code of their program available.
765 @node GFORTRAN_ERROR_BACKTRACE
766 @section @env{GFORTRAN_ERROR_BACKTRACE}---Show backtrace on run-time errors
768 If the @env{GFORTRAN_ERROR_BACKTRACE} variable is set to @samp{y},
769 @samp{Y} or @samp{1} (only the first letter is relevant) then a
770 backtrace is printed when a serious run-time error occurs.  To disable
771 the backtracing, set the variable to @samp{n}, @samp{N}, @samp{0}.
772 Default is to print a backtrace unless the @option{-fno-backtrace}
773 compile option was used.
775 @c =====================================================================
776 @c PART II: LANGUAGE REFERENCE
777 @c =====================================================================
779 @tex
780 \part{II}{Language Reference}
781 @end tex
783 @c ---------------------------------------------------------------------
784 @c Fortran 2003 and 2008 Status
785 @c ---------------------------------------------------------------------
787 @node Fortran 2003 and 2008 status
788 @chapter Fortran 2003 and 2008 Status
790 @menu
791 * Fortran 2003 status::
792 * Fortran 2008 status::
793 * TS 29113 status::
794 @end menu
796 @node Fortran 2003 status
797 @section Fortran 2003 status
799 GNU Fortran supports several Fortran 2003 features; an incomplete
800 list can be found below.  See also the
801 @uref{http://gcc.gnu.org/wiki/Fortran2003, wiki page} about Fortran 2003.
803 @itemize
804 @item Procedure pointers including procedure-pointer components with
805 @code{PASS} attribute.
807 @item Procedures which are bound to a derived type (type-bound procedures)
808 including @code{PASS}, @code{PROCEDURE} and @code{GENERIC}, and
809 operators bound to a type.
811 @item Abstract interfaces and type extension with the possibility to
812 override type-bound procedures or to have deferred binding.
814 @item Polymorphic entities (``@code{CLASS}'') for derived types -- including
815 @code{SAME_TYPE_AS}, @code{EXTENDS_TYPE_OF} and @code{SELECT TYPE} for
816 scalars and arrays, including unlimited polymorphism.
818 @item Generic interface names, which have the same name as derived types,
819 are now supported. This allows one to write constructor functions.  Note
820 that Fortran does not support static constructor functions.  For static
821 variables, only default initialization or structure-constructor
822 initialization are available.
824 @item The @code{ASSOCIATE} construct.
826 @item Interoperability with C including enumerations, 
828 @item In structure constructors the components with default values may be
829 omitted.
831 @item Extensions to the @code{ALLOCATE} statement, allowing for a
832 type-specification with type parameter and for allocation and initialization
833 from a @code{SOURCE=} expression; @code{ALLOCATE} and @code{DEALLOCATE}
834 optionally return an error message string via @code{ERRMSG=}.
836 @item Reallocation on assignment: If an intrinsic assignment is
837 used, an allocatable variable on the left-hand side is automatically allocated
838 (if unallocated) or reallocated (if the shape is different). Currently, scalar
839 deferred character length left-hand sides are correctly handled but arrays
840 are not yet fully implemented.
842 @item Transferring of allocations via @code{MOVE_ALLOC}.
844 @item The @code{PRIVATE} and @code{PUBLIC} attributes may be given individually
845 to derived-type components.
847 @item In pointer assignments, the lower bound may be specified and
848 the remapping of elements is supported.
850 @item For pointers an @code{INTENT} may be specified which affect the
851 association status not the value of the pointer target.
853 @item Intrinsics @code{command_argument_count}, @code{get_command},
854 @code{get_command_argument}, and @code{get_environment_variable}.
856 @item Support for Unicode characters (ISO 10646) and UTF-8, including
857 the @code{SELECTED_CHAR_KIND} and @code{NEW_LINE} intrinsic functions.
859 @item Support for binary, octal and hexadecimal (BOZ) constants in the
860 intrinsic functions @code{INT}, @code{REAL}, @code{CMPLX} and @code{DBLE}.
862 @item Support for namelist variables with allocatable and pointer
863 attribute and nonconstant length type parameter.
865 @item
866 @cindex array, constructors
867 @cindex @code{[...]}
868 Array constructors using square brackets.  That is, @code{[...]} rather
869 than @code{(/.../)}.  Type-specification for array constructors like
870 @code{(/ some-type :: ... /)}.
872 @item Extensions to the specification and initialization expressions,
873 including the support for intrinsics with real and complex arguments.
875 @item Support for the asynchronous input/output syntax; however, the
876 data transfer is currently always synchronously performed. 
878 @item
879 @cindex @code{FLUSH} statement
880 @cindex statement, @code{FLUSH}
881 @code{FLUSH} statement.
883 @item
884 @cindex @code{IOMSG=} specifier
885 @code{IOMSG=} specifier for I/O statements.
887 @item
888 @cindex @code{ENUM} statement
889 @cindex @code{ENUMERATOR} statement
890 @cindex statement, @code{ENUM}
891 @cindex statement, @code{ENUMERATOR}
892 @opindex @code{fshort-enums}
893 Support for the declaration of enumeration constants via the
894 @code{ENUM} and @code{ENUMERATOR} statements.  Interoperability with
895 @command{gcc} is guaranteed also for the case where the
896 @command{-fshort-enums} command line option is given.
898 @item
899 @cindex TR 15581
900 TR 15581:
901 @itemize
902 @item
903 @cindex @code{ALLOCATABLE} dummy arguments
904 @code{ALLOCATABLE} dummy arguments.
905 @item
906 @cindex @code{ALLOCATABLE} function results
907 @code{ALLOCATABLE} function results
908 @item
909 @cindex @code{ALLOCATABLE} components of derived types
910 @code{ALLOCATABLE} components of derived types
911 @end itemize
913 @item
914 @cindex @code{STREAM} I/O
915 @cindex @code{ACCESS='STREAM'} I/O
916 The @code{OPEN} statement supports the @code{ACCESS='STREAM'} specifier,
917 allowing I/O without any record structure.
919 @item
920 Namelist input/output for internal files.
922 @item Further I/O extensions: Rounding during formatted output, using of
923 a decimal comma instead of a decimal point, setting whether a plus sign
924 should appear for positive numbers.
926 @item
927 @cindex @code{PROTECTED} statement
928 @cindex statement, @code{PROTECTED}
929 The @code{PROTECTED} statement and attribute.
931 @item
932 @cindex @code{VALUE} statement
933 @cindex statement, @code{VALUE}
934 The @code{VALUE} statement and attribute.
936 @item
937 @cindex @code{VOLATILE} statement
938 @cindex statement, @code{VOLATILE}
939 The @code{VOLATILE} statement and attribute.
941 @item
942 @cindex @code{IMPORT} statement
943 @cindex statement, @code{IMPORT}
944 The @code{IMPORT} statement, allowing to import
945 host-associated derived types.
947 @item The intrinsic modules @code{ISO_FORTRAN_ENVIRONMENT} is supported,
948 which contains parameters of the I/O units, storage sizes. Additionally,
949 procedures for C interoperability are available in the @code{ISO_C_BINDING}
950 module.
952 @item
953 @cindex @code{USE, INTRINSIC} statement
954 @cindex statement, @code{USE, INTRINSIC}
955 @cindex @code{ISO_FORTRAN_ENV} statement
956 @cindex statement, @code{ISO_FORTRAN_ENV}
957 @code{USE} statement with @code{INTRINSIC} and @code{NON_INTRINSIC}
958 attribute; supported intrinsic modules: @code{ISO_FORTRAN_ENV},
959 @code{ISO_C_BINDING}, @code{OMP_LIB} and @code{OMP_LIB_KINDS}.
961 @item
962 Renaming of operators in the @code{USE} statement.
964 @end itemize
967 @node Fortran 2008 status
968 @section Fortran 2008 status
970 The latest version of the Fortran standard is ISO/IEC 1539-1:2010, informally
971 known as Fortran 2008.  The official version is available from International
972 Organization for Standardization (ISO) or its national member organizations.
973 The the final draft (FDIS) can be downloaded free of charge from
974 @url{http://www.nag.co.uk/@/sc22wg5/@/links.html}.  Fortran is developed by the
975 Working Group 5 of Sub-Committee 22 of the Joint Technical Committee 1 of the
976 International Organization for Standardization and the International
977 Electrotechnical Commission (IEC).  This group is known as
978 @uref{http://www.nag.co.uk/sc22wg5/, WG5}.
980 The GNU Fortran compiler supports several of the new features of Fortran 2008;
981 the @uref{http://gcc.gnu.org/wiki/Fortran2008Status, wiki} has some information
982 about the current Fortran 2008 implementation status.  In particular, the
983 following is implemented.
985 @itemize
986 @item The @option{-std=f2008} option and support for the file extensions 
987 @file{.f08} and @file{.F08}.
989 @item The @code{OPEN} statement now supports the @code{NEWUNIT=} option,
990 which returns a unique file unit, thus preventing inadvertent use of the
991 same unit in different parts of the program.
993 @item The @code{g0} format descriptor and unlimited format items.
995 @item The mathematical intrinsics @code{ASINH}, @code{ACOSH}, @code{ATANH},
996 @code{ERF}, @code{ERFC}, @code{GAMMA}, @code{LOG_GAMMA}, @code{BESSEL_J0},
997 @code{BESSEL_J1}, @code{BESSEL_JN}, @code{BESSEL_Y0}, @code{BESSEL_Y1},
998 @code{BESSEL_YN}, @code{HYPOT}, @code{NORM2}, and @code{ERFC_SCALED}.
1000 @item Using complex arguments with @code{TAN}, @code{SINH}, @code{COSH},
1001 @code{TANH}, @code{ASIN}, @code{ACOS}, and @code{ATAN} is now possible;
1002 @code{ATAN}(@var{Y},@var{X}) is now an alias for @code{ATAN2}(@var{Y},@var{X}).
1004 @item Support of the @code{PARITY} intrinsic functions.
1006 @item The following bit intrinsics: @code{LEADZ} and @code{TRAILZ} for
1007 counting the number of leading and trailing zero bits, @code{POPCNT} and
1008 @code{POPPAR} for counting the number of one bits and returning the parity;
1009 @code{BGE}, @code{BGT}, @code{BLE}, and @code{BLT} for bitwise comparisons;
1010 @code{DSHIFTL} and @code{DSHIFTR} for combined left and right shifts,
1011 @code{MASKL} and @code{MASKR} for simple left and right justified masks,
1012 @code{MERGE_BITS} for a bitwise merge using a mask, @code{SHIFTA},
1013 @code{SHIFTL} and @code{SHIFTR} for shift operations, and the
1014 transformational bit intrinsics @code{IALL}, @code{IANY} and @code{IPARITY}.
1016 @item Support of the @code{EXECUTE_COMMAND_LINE} intrinsic subroutine.
1018 @item Support for the @code{STORAGE_SIZE} intrinsic inquiry function.
1020 @item The @code{INT@{8,16,32@}} and @code{REAL@{32,64,128@}} kind type
1021 parameters and the array-valued named constants @code{INTEGER_KINDS},
1022 @code{LOGICAL_KINDS}, @code{REAL_KINDS} and @code{CHARACTER_KINDS} of
1023 the intrinsic module @code{ISO_FORTRAN_ENV}.
1025 @item The module procedures @code{C_SIZEOF} of the intrinsic module
1026 @code{ISO_C_BINDINGS} and @code{COMPILER_VERSION} and @code{COMPILER_OPTIONS}
1027 of @code{ISO_FORTRAN_ENV}.
1029 @item Coarray support for serial programs with @option{-fcoarray=single} flag
1030 and experimental support for multiple images with the @option{-fcoarray=lib}
1031 flag.
1033 @item The @code{DO CONCURRENT} construct is supported.
1035 @item The @code{BLOCK} construct is supported.
1037 @item The @code{STOP} and the new @code{ERROR STOP} statements now
1038 support all constant expressions.
1040 @item Support for the @code{CONTIGUOUS} attribute.
1042 @item Support for @code{ALLOCATE} with @code{MOLD}.
1044 @item Support for the @code{IMPURE} attribute for procedures, which
1045 allows for @code{ELEMENTAL} procedures without the restrictions of
1046 @code{PURE}.
1048 @item Null pointers (including @code{NULL()}) and not-allocated variables
1049 can be used as actual argument to optional non-pointer, non-allocatable
1050 dummy arguments, denoting an absent argument.
1052 @item Non-pointer variables with @code{TARGET} attribute can be used as
1053 actual argument to @code{POINTER} dummies with @code{INTENT(IN)}.
1055 @item Pointers including procedure pointers and those in a derived
1056 type (pointer components) can now be initialized by a target instead
1057 of only by @code{NULL}.
1059 @item The @code{EXIT} statement (with construct-name) can be now be
1060 used to leave not only the @code{DO} but also the @code{ASSOCIATE},
1061 @code{BLOCK}, @code{IF}, @code{SELECT CASE} and @code{SELECT TYPE}
1062 constructs.
1064 @item Internal procedures can now be used as actual argument.
1066 @item Minor features: obsolesce diagnostics for @code{ENTRY} with
1067 @option{-std=f2008}; a line may start with a semicolon; for internal
1068 and module procedures @code{END} can be used instead of
1069 @code{END SUBROUTINE} and @code{END FUNCTION}; @code{SELECTED_REAL_KIND}
1070 now also takes a @code{RADIX} argument; intrinsic types are supported
1071 for @code{TYPE}(@var{intrinsic-type-spec}); multiple type-bound procedures
1072 can be declared in a single @code{PROCEDURE} statement; implied-shape
1073 arrays are supported for named constants (@code{PARAMETER}).
1074 @end itemize
1078 @node TS 29113 status
1079 @section Technical Specification 29113 Status
1081 GNU Fortran supports some of the new features of the Technical
1082 Specification (TS) 29113 on Further Interoperability of Fortran with C.
1083 The @uref{http://gcc.gnu.org/wiki/TS29113Status, wiki} has some information
1084 about the current TS 29113 implementation status.  In particular, the
1085 following is implemented.
1087 See also @ref{Further Interoperability of Fortran with C}.
1089 @itemize
1090 @item The @option{-std=f2008ts} option.
1092 @item The @code{OPTIONAL} attribute is allowed for dummy arguments
1093 of @code{BIND(C) procedures.}
1095 @item The @code{RANK} intrinsic is supported.
1097 @item GNU Fortran's implementation for variables with @code{ASYNCHRONOUS}
1098 attribute is compatible with TS 29113.
1100 @item Assumed types (@code{TYPE(*)}.
1102 @item Assumed-rank (@code{DIMENSION(..)}). However, the array descriptor
1103 of the TS is not yet supported.
1104 @end itemize
1108 @c ---------------------------------------------------------------------
1109 @c Compiler Characteristics
1110 @c ---------------------------------------------------------------------
1112 @node Compiler Characteristics
1113 @chapter Compiler Characteristics
1115 This chapter describes certain characteristics of the GNU Fortran
1116 compiler, that are not specified by the Fortran standard, but which
1117 might in some way or another become visible to the programmer.
1119 @menu
1120 * KIND Type Parameters::
1121 * Internal representation of LOGICAL variables::
1122 * Thread-safety of the runtime library::
1123 * Data consistency and durability::
1124 @end menu
1127 @node KIND Type Parameters
1128 @section KIND Type Parameters
1129 @cindex kind
1131 The @code{KIND} type parameters supported by GNU Fortran for the primitive
1132 data types are:
1134 @table @code
1136 @item INTEGER
1137 1, 2, 4, 8*, 16*, default: 4 (1)
1139 @item LOGICAL
1140 1, 2, 4, 8*, 16*, default: 4 (1)
1142 @item REAL
1143 4, 8, 10*, 16*, default: 4 (2)
1145 @item COMPLEX
1146 4, 8, 10*, 16*, default: 4 (2)
1148 @item CHARACTER
1149 1, 4, default: 1
1151 @end table
1153 @noindent
1154 * = not available on all systems @*
1155 (1) Unless -fdefault-integer-8 is used @*
1156 (2) Unless -fdefault-real-8 is used
1158 @noindent
1159 The @code{KIND} value matches the storage size in bytes, except for
1160 @code{COMPLEX} where the storage size is twice as much (or both real and
1161 imaginary part are a real value of the given size).  It is recommended to use
1162 the @code{SELECTED_CHAR_KIND}, @code{SELECTED_INT_KIND} and
1163 @code{SELECTED_REAL_KIND} intrinsics or the @code{INT8}, @code{INT16},
1164 @code{INT32}, @code{INT64}, @code{REAL32}, @code{REAL64}, and @code{REAL128}
1165 parameters of the @code{ISO_FORTRAN_ENV} module instead of the concrete values.
1166 The available kind parameters can be found in the constant arrays
1167 @code{CHARACTER_KINDS}, @code{INTEGER_KINDS}, @code{LOGICAL_KINDS} and
1168 @code{REAL_KINDS} in the @code{ISO_FORTRAN_ENV} module
1169 (see @ref{ISO_FORTRAN_ENV}).  For C interoperability, the kind parameters of
1170 the @code{ISO_C_BINDING} module should be used (see @ref{ISO_C_BINDING}).
1173 @node Internal representation of LOGICAL variables
1174 @section Internal representation of LOGICAL variables
1175 @cindex logical, variable representation
1177 The Fortran standard does not specify how variables of @code{LOGICAL}
1178 type are represented, beyond requiring that @code{LOGICAL} variables
1179 of default kind have the same storage size as default @code{INTEGER}
1180 and @code{REAL} variables.  The GNU Fortran internal representation is
1181 as follows.
1183 A @code{LOGICAL(KIND=N)} variable is represented as an
1184 @code{INTEGER(KIND=N)} variable, however, with only two permissible
1185 values: @code{1} for @code{.TRUE.} and @code{0} for
1186 @code{.FALSE.}.  Any other integer value results in undefined behavior.
1188 See also @ref{Argument passing conventions} and @ref{Interoperability with C}.
1191 @node Thread-safety of the runtime library
1192 @section Thread-safety of the runtime library
1193 @cindex thread-safety, threads
1195 GNU Fortran can be used in programs with multiple threads, e.g.@: by
1196 using OpenMP, by calling OS thread handling functions via the
1197 @code{ISO_C_BINDING} facility, or by GNU Fortran compiled library code
1198 being called from a multi-threaded program.
1200 The GNU Fortran runtime library, (@code{libgfortran}), supports being
1201 called concurrently from multiple threads with the following
1202 exceptions. 
1204 During library initialization, the C @code{getenv} function is used,
1205 which need not be thread-safe.  Similarly, the @code{getenv}
1206 function is used to implement the @code{GET_ENVIRONMENT_VARIABLE} and
1207 @code{GETENV} intrinsics.  It is the responsibility of the user to
1208 ensure that the environment is not being updated concurrently when any
1209 of these actions are taking place.
1211 The @code{EXECUTE_COMMAND_LINE} and @code{SYSTEM} intrinsics are
1212 implemented with the @code{system} function, which need not be
1213 thread-safe.  It is the responsibility of the user to ensure that
1214 @code{system} is not called concurrently.
1216 Finally, for platforms not supporting thread-safe POSIX functions,
1217 further functionality might not be thread-safe.  For details, please
1218 consult the documentation for your operating system.
1221 @node Data consistency and durability
1222 @section Data consistency and durability
1223 @cindex consistency, durability
1225 This section contains a brief overview of data and metadata
1226 consistency and durability issues when doing I/O.
1228 With respect to durability, GNU Fortran makes no effort to ensure that
1229 data is committed to stable storage. If this is required, the GNU
1230 Fortran programmer can use the intrinsic @code{FNUM} to retrieve the
1231 low level file descriptor corresponding to an open Fortran unit. Then,
1232 using e.g. the @code{ISO_C_BINDING} feature, one can call the
1233 underlying system call to flush dirty data to stable storage, such as
1234 @code{fsync} on POSIX, @code{_commit} on MingW, or @code{fcntl(fd,
1235 F_FULLSYNC, 0)} on Mac OS X. The following example shows how to call
1236 fsync:
1238 @smallexample
1239   ! Declare the interface for POSIX fsync function
1240   interface
1241     function fsync (fd) bind(c,name="fsync")
1242     use iso_c_binding, only: c_int
1243       integer(c_int), value :: fd
1244       integer(c_int) :: fsync
1245     end function fsync
1246   end interface
1248   ! Variable declaration
1249   integer :: ret
1251   ! Opening unit 10
1252   open (10,file="foo")
1254   ! ...
1255   ! Perform I/O on unit 10
1256   ! ...
1258   ! Flush and sync
1259   flush(10)
1260   ret = fsync(fnum(10))
1262   ! Handle possible error
1263   if (ret /= 0) stop "Error calling FSYNC"
1264 @end smallexample
1266 With respect to consistency, for regular files GNU Fortran uses
1267 buffered I/O in order to improve performance. This buffer is flushed
1268 automatically when full and in some other situations, e.g. when
1269 closing a unit. It can also be explicitly flushed with the
1270 @code{FLUSH} statement. Also, the buffering can be turned off with the
1271 @code{GFORTRAN_UNBUFFERED_ALL} and
1272 @code{GFORTRAN_UNBUFFERED_PRECONNECTED} environment variables. Special
1273 files, such as terminals and pipes, are always unbuffered. Sometimes,
1274 however, further things may need to be done in order to allow other
1275 processes to see data that GNU Fortran has written, as follows.
1277 The Windows platform supports a relaxed metadata consistency model,
1278 where file metadata is written to the directory lazily. This means
1279 that, for instance, the @code{dir} command can show a stale size for a
1280 file. One can force a directory metadata update by closing the unit,
1281 or by calling @code{_commit} on the file descriptor. Note, though,
1282 that @code{_commit} will force all dirty data to stable storage, which
1283 is often a very slow operation.
1285 The Network File System (NFS) implements a relaxed consistency model
1286 called open-to-close consistency. Closing a file forces dirty data and
1287 metadata to be flushed to the server, and opening a file forces the
1288 client to contact the server in order to revalidate cached
1289 data. @code{fsync} will also force a flush of dirty data and metadata
1290 to the server. Similar to @code{open} and @code{close}, acquiring and
1291 releasing @code{fcntl} file locks, if the server supports them, will
1292 also force cache validation and flushing dirty data and metadata.
1295 @c ---------------------------------------------------------------------
1296 @c Extensions
1297 @c ---------------------------------------------------------------------
1299 @c Maybe this chapter should be merged with the 'Standards' section,
1300 @c whenever that is written :-)
1302 @node Extensions
1303 @chapter Extensions
1304 @cindex extensions
1306 The two sections below detail the extensions to standard Fortran that are
1307 implemented in GNU Fortran, as well as some of the popular or
1308 historically important extensions that are not (or not yet) implemented.
1309 For the latter case, we explain the alternatives available to GNU Fortran
1310 users, including replacement by standard-conforming code or GNU
1311 extensions.
1313 @menu
1314 * Extensions implemented in GNU Fortran::
1315 * Extensions not implemented in GNU Fortran::
1316 @end menu
1319 @node Extensions implemented in GNU Fortran
1320 @section Extensions implemented in GNU Fortran
1321 @cindex extensions, implemented
1323 GNU Fortran implements a number of extensions over standard
1324 Fortran.  This chapter contains information on their syntax and
1325 meaning.  There are currently two categories of GNU Fortran
1326 extensions, those that provide functionality beyond that provided
1327 by any standard, and those that are supported by GNU Fortran
1328 purely for backward compatibility with legacy compilers.  By default,
1329 @option{-std=gnu} allows the compiler to accept both types of
1330 extensions, but to warn about the use of the latter.  Specifying
1331 either @option{-std=f95}, @option{-std=f2003} or @option{-std=f2008}
1332 disables both types of extensions, and @option{-std=legacy} allows both
1333 without warning.
1335 @menu
1336 * Old-style kind specifications::
1337 * Old-style variable initialization::
1338 * Extensions to namelist::
1339 * X format descriptor without count field::
1340 * Commas in FORMAT specifications::
1341 * Missing period in FORMAT specifications::
1342 * I/O item lists::
1343 * @code{Q} exponent-letter::
1344 * BOZ literal constants::
1345 * Real array indices::
1346 * Unary operators::
1347 * Implicitly convert LOGICAL and INTEGER values::
1348 * Hollerith constants support::
1349 * Cray pointers::
1350 * CONVERT specifier::
1351 * OpenMP::
1352 * Argument list functions::
1353 @end menu
1355 @node Old-style kind specifications
1356 @subsection Old-style kind specifications
1357 @cindex kind, old-style
1359 GNU Fortran allows old-style kind specifications in declarations.  These
1360 look like:
1361 @smallexample
1362       TYPESPEC*size x,y,z
1363 @end smallexample
1364 @noindent
1365 where @code{TYPESPEC} is a basic type (@code{INTEGER}, @code{REAL},
1366 etc.), and where @code{size} is a byte count corresponding to the
1367 storage size of a valid kind for that type.  (For @code{COMPLEX}
1368 variables, @code{size} is the total size of the real and imaginary
1369 parts.)  The statement then declares @code{x}, @code{y} and @code{z} to
1370 be of type @code{TYPESPEC} with the appropriate kind.  This is
1371 equivalent to the standard-conforming declaration
1372 @smallexample
1373       TYPESPEC(k) x,y,z
1374 @end smallexample
1375 @noindent
1376 where @code{k} is the kind parameter suitable for the intended precision.  As
1377 kind parameters are implementation-dependent, use the @code{KIND},
1378 @code{SELECTED_INT_KIND} and @code{SELECTED_REAL_KIND} intrinsics to retrieve
1379 the correct value, for instance @code{REAL*8 x} can be replaced by:
1380 @smallexample
1381 INTEGER, PARAMETER :: dbl = KIND(1.0d0)
1382 REAL(KIND=dbl) :: x
1383 @end smallexample
1385 @node Old-style variable initialization
1386 @subsection Old-style variable initialization
1388 GNU Fortran allows old-style initialization of variables of the
1389 form:
1390 @smallexample
1391       INTEGER i/1/,j/2/
1392       REAL x(2,2) /3*0.,1./
1393 @end smallexample
1394 The syntax for the initializers is as for the @code{DATA} statement, but
1395 unlike in a @code{DATA} statement, an initializer only applies to the
1396 variable immediately preceding the initialization.  In other words,
1397 something like @code{INTEGER I,J/2,3/} is not valid.  This style of
1398 initialization is only allowed in declarations without double colons
1399 (@code{::}); the double colons were introduced in Fortran 90, which also
1400 introduced a standard syntax for initializing variables in type
1401 declarations.
1403 Examples of standard-conforming code equivalent to the above example
1404 are:
1405 @smallexample
1406 ! Fortran 90
1407       INTEGER :: i = 1, j = 2
1408       REAL :: x(2,2) = RESHAPE((/0.,0.,0.,1./),SHAPE(x))
1409 ! Fortran 77
1410       INTEGER i, j
1411       REAL x(2,2)
1412       DATA i/1/, j/2/, x/3*0.,1./
1413 @end smallexample
1415 Note that variables which are explicitly initialized in declarations
1416 or in @code{DATA} statements automatically acquire the @code{SAVE}
1417 attribute.
1419 @node Extensions to namelist
1420 @subsection Extensions to namelist
1421 @cindex Namelist
1423 GNU Fortran fully supports the Fortran 95 standard for namelist I/O
1424 including array qualifiers, substrings and fully qualified derived types.
1425 The output from a namelist write is compatible with namelist read.  The
1426 output has all names in upper case and indentation to column 1 after the
1427 namelist name.  Two extensions are permitted:
1429 Old-style use of @samp{$} instead of @samp{&}
1430 @smallexample
1431 $MYNML
1432  X(:)%Y(2) = 1.0 2.0 3.0
1433  CH(1:4) = "abcd"
1434 $END
1435 @end smallexample
1437 It should be noted that the default terminator is @samp{/} rather than
1438 @samp{&END}.
1440 Querying of the namelist when inputting from stdin.  After at least
1441 one space, entering @samp{?} sends to stdout the namelist name and the names of
1442 the variables in the namelist:
1443 @smallexample
1446 &mynml
1448  x%y
1449  ch
1450 &end
1451 @end smallexample
1453 Entering @samp{=?} outputs the namelist to stdout, as if
1454 @code{WRITE(*,NML = mynml)} had been called:
1455 @smallexample
1458 &MYNML
1459  X(1)%Y=  0.000000    ,  1.000000    ,  0.000000    ,
1460  X(2)%Y=  0.000000    ,  2.000000    ,  0.000000    ,
1461  X(3)%Y=  0.000000    ,  3.000000    ,  0.000000    ,
1462  CH=abcd,  /
1463 @end smallexample
1465 To aid this dialog, when input is from stdin, errors send their
1466 messages to stderr and execution continues, even if @code{IOSTAT} is set.
1468 @code{PRINT} namelist is permitted.  This causes an error if
1469 @option{-std=f95} is used.
1470 @smallexample
1471 PROGRAM test_print
1472   REAL, dimension (4)  ::  x = (/1.0, 2.0, 3.0, 4.0/)
1473   NAMELIST /mynml/ x
1474   PRINT mynml
1475 END PROGRAM test_print
1476 @end smallexample
1478 Expanded namelist reads are permitted.  This causes an error if 
1479 @option{-std=f95} is used.  In the following example, the first element
1480 of the array will be given the value 0.00 and the two succeeding
1481 elements will be given the values 1.00 and 2.00.
1482 @smallexample
1483 &MYNML
1484   X(1,1) = 0.00 , 1.00 , 2.00
1486 @end smallexample
1488 @node X format descriptor without count field
1489 @subsection @code{X} format descriptor without count field
1491 To support legacy codes, GNU Fortran permits the count field of the
1492 @code{X} edit descriptor in @code{FORMAT} statements to be omitted.
1493 When omitted, the count is implicitly assumed to be one.
1495 @smallexample
1496        PRINT 10, 2, 3
1497 10     FORMAT (I1, X, I1)
1498 @end smallexample
1500 @node Commas in FORMAT specifications
1501 @subsection Commas in @code{FORMAT} specifications
1503 To support legacy codes, GNU Fortran allows the comma separator
1504 to be omitted immediately before and after character string edit
1505 descriptors in @code{FORMAT} statements.
1507 @smallexample
1508        PRINT 10, 2, 3
1509 10     FORMAT ('FOO='I1' BAR='I2)
1510 @end smallexample
1513 @node Missing period in FORMAT specifications
1514 @subsection Missing period in @code{FORMAT} specifications
1516 To support legacy codes, GNU Fortran allows missing periods in format
1517 specifications if and only if @option{-std=legacy} is given on the
1518 command line.  This is considered non-conforming code and is
1519 discouraged.
1521 @smallexample
1522        REAL :: value
1523        READ(*,10) value
1524 10     FORMAT ('F4')
1525 @end smallexample
1527 @node I/O item lists
1528 @subsection I/O item lists
1529 @cindex I/O item lists
1531 To support legacy codes, GNU Fortran allows the input item list
1532 of the @code{READ} statement, and the output item lists of the
1533 @code{WRITE} and @code{PRINT} statements, to start with a comma.
1535 @node @code{Q} exponent-letter
1536 @subsection @code{Q} exponent-letter
1537 @cindex @code{Q} exponent-letter
1539 GNU Fortran accepts real literal constants with an exponent-letter
1540 of @code{Q}, for example, @code{1.23Q45}.  The constant is interpreted
1541 as a @code{REAL(16)} entity on targets that support this type.  If
1542 the target does not support @code{REAL(16)} but has a @code{REAL(10)}
1543 type, then the real-literal-constant will be interpreted as a
1544 @code{REAL(10)} entity.  In the absence of @code{REAL(16)} and
1545 @code{REAL(10)}, an error will occur.
1547 @node BOZ literal constants
1548 @subsection BOZ literal constants
1549 @cindex BOZ literal constants
1551 Besides decimal constants, Fortran also supports binary (@code{b}),
1552 octal (@code{o}) and hexadecimal (@code{z}) integer constants.  The
1553 syntax is: @samp{prefix quote digits quote}, were the prefix is
1554 either @code{b}, @code{o} or @code{z}, quote is either @code{'} or
1555 @code{"} and the digits are for binary @code{0} or @code{1}, for
1556 octal between @code{0} and @code{7}, and for hexadecimal between
1557 @code{0} and @code{F}.  (Example: @code{b'01011101'}.)
1559 Up to Fortran 95, BOZ literals were only allowed to initialize
1560 integer variables in DATA statements.  Since Fortran 2003 BOZ literals
1561 are also allowed as argument of @code{REAL}, @code{DBLE}, @code{INT}
1562 and @code{CMPLX}; the result is the same as if the integer BOZ
1563 literal had been converted by @code{TRANSFER} to, respectively,
1564 @code{real}, @code{double precision}, @code{integer} or @code{complex}.
1565 As GNU Fortran extension the intrinsic procedures @code{FLOAT},
1566 @code{DFLOAT}, @code{COMPLEX} and @code{DCMPLX} are treated alike.
1568 As an extension, GNU Fortran allows hexadecimal BOZ literal constants to
1569 be specified using the @code{X} prefix, in addition to the standard
1570 @code{Z} prefix.  The BOZ literal can also be specified by adding a
1571 suffix to the string, for example, @code{Z'ABC'} and @code{'ABC'Z} are
1572 equivalent.
1574 Furthermore, GNU Fortran allows using BOZ literal constants outside
1575 DATA statements and the four intrinsic functions allowed by Fortran 2003.
1576 In DATA statements, in direct assignments, where the right-hand side
1577 only contains a BOZ literal constant, and for old-style initializers of
1578 the form @code{integer i /o'0173'/}, the constant is transferred
1579 as if @code{TRANSFER} had been used; for @code{COMPLEX} numbers, only
1580 the real part is initialized unless @code{CMPLX} is used.  In all other
1581 cases, the BOZ literal constant is converted to an @code{INTEGER} value with
1582 the largest decimal representation.  This value is then converted
1583 numerically to the type and kind of the variable in question.
1584 (For instance, @code{real :: r = b'0000001' + 1} initializes @code{r}
1585 with @code{2.0}.) As different compilers implement the extension
1586 differently, one should be careful when doing bitwise initialization
1587 of non-integer variables.
1589 Note that initializing an @code{INTEGER} variable with a statement such
1590 as @code{DATA i/Z'FFFFFFFF'/} will give an integer overflow error rather
1591 than the desired result of @math{-1} when @code{i} is a 32-bit integer
1592 on a system that supports 64-bit integers.  The @samp{-fno-range-check}
1593 option can be used as a workaround for legacy code that initializes
1594 integers in this manner.
1596 @node Real array indices
1597 @subsection Real array indices
1598 @cindex array, indices of type real
1600 As an extension, GNU Fortran allows the use of @code{REAL} expressions
1601 or variables as array indices.
1603 @node Unary operators
1604 @subsection Unary operators
1605 @cindex operators, unary
1607 As an extension, GNU Fortran allows unary plus and unary minus operators
1608 to appear as the second operand of binary arithmetic operators without
1609 the need for parenthesis.
1611 @smallexample
1612        X = Y * -Z
1613 @end smallexample
1615 @node Implicitly convert LOGICAL and INTEGER values
1616 @subsection Implicitly convert @code{LOGICAL} and @code{INTEGER} values
1617 @cindex conversion, to integer
1618 @cindex conversion, to logical
1620 As an extension for backwards compatibility with other compilers, GNU
1621 Fortran allows the implicit conversion of @code{LOGICAL} values to
1622 @code{INTEGER} values and vice versa.  When converting from a
1623 @code{LOGICAL} to an @code{INTEGER}, @code{.FALSE.} is interpreted as
1624 zero, and @code{.TRUE.} is interpreted as one.  When converting from
1625 @code{INTEGER} to @code{LOGICAL}, the value zero is interpreted as
1626 @code{.FALSE.} and any nonzero value is interpreted as @code{.TRUE.}.
1628 @smallexample
1629         LOGICAL :: l
1630         l = 1
1631 @end smallexample
1632 @smallexample
1633         INTEGER :: i
1634         i = .TRUE.
1635 @end smallexample
1637 However, there is no implicit conversion of @code{INTEGER} values in
1638 @code{if}-statements, nor of @code{LOGICAL} or @code{INTEGER} values
1639 in I/O operations.
1641 @node Hollerith constants support
1642 @subsection Hollerith constants support
1643 @cindex Hollerith constants
1645 GNU Fortran supports Hollerith constants in assignments, function
1646 arguments, and @code{DATA} and @code{ASSIGN} statements.  A Hollerith
1647 constant is written as a string of characters preceded by an integer
1648 constant indicating the character count, and the letter @code{H} or
1649 @code{h}, and stored in bytewise fashion in a numeric (@code{INTEGER},
1650 @code{REAL}, or @code{complex}) or @code{LOGICAL} variable.  The
1651 constant will be padded or truncated to fit the size of the variable in
1652 which it is stored.
1654 Examples of valid uses of Hollerith constants:
1655 @smallexample
1656       complex*16 x(2)
1657       data x /16Habcdefghijklmnop, 16Hqrstuvwxyz012345/
1658       x(1) = 16HABCDEFGHIJKLMNOP
1659       call foo (4h abc)
1660 @end smallexample
1662 Invalid Hollerith constants examples:
1663 @smallexample
1664       integer*4 a
1665       a = 8H12345678 ! Valid, but the Hollerith constant will be truncated.
1666       a = 0H         ! At least one character is needed.
1667 @end smallexample
1669 In general, Hollerith constants were used to provide a rudimentary
1670 facility for handling character strings in early Fortran compilers,
1671 prior to the introduction of @code{CHARACTER} variables in Fortran 77;
1672 in those cases, the standard-compliant equivalent is to convert the
1673 program to use proper character strings.  On occasion, there may be a
1674 case where the intent is specifically to initialize a numeric variable
1675 with a given byte sequence.  In these cases, the same result can be
1676 obtained by using the @code{TRANSFER} statement, as in this example.
1677 @smallexample
1678       INTEGER(KIND=4) :: a
1679       a = TRANSFER ("abcd", a)     ! equivalent to: a = 4Habcd
1680 @end smallexample
1683 @node Cray pointers
1684 @subsection Cray pointers
1685 @cindex pointer, Cray
1687 Cray pointers are part of a non-standard extension that provides a
1688 C-like pointer in Fortran.  This is accomplished through a pair of
1689 variables: an integer "pointer" that holds a memory address, and a
1690 "pointee" that is used to dereference the pointer.
1692 Pointer/pointee pairs are declared in statements of the form:
1693 @smallexample
1694         pointer ( <pointer> , <pointee> )
1695 @end smallexample
1697 @smallexample
1698         pointer ( <pointer1> , <pointee1> ), ( <pointer2> , <pointee2> ), ...
1699 @end smallexample
1700 The pointer is an integer that is intended to hold a memory address.
1701 The pointee may be an array or scalar.  A pointee can be an assumed
1702 size array---that is, the last dimension may be left unspecified by
1703 using a @code{*} in place of a value---but a pointee cannot be an
1704 assumed shape array.  No space is allocated for the pointee.
1706 The pointee may have its type declared before or after the pointer
1707 statement, and its array specification (if any) may be declared
1708 before, during, or after the pointer statement.  The pointer may be
1709 declared as an integer prior to the pointer statement.  However, some
1710 machines have default integer sizes that are different than the size
1711 of a pointer, and so the following code is not portable:
1712 @smallexample
1713         integer ipt
1714         pointer (ipt, iarr)
1715 @end smallexample
1716 If a pointer is declared with a kind that is too small, the compiler
1717 will issue a warning; the resulting binary will probably not work
1718 correctly, because the memory addresses stored in the pointers may be
1719 truncated.  It is safer to omit the first line of the above example;
1720 if explicit declaration of ipt's type is omitted, then the compiler
1721 will ensure that ipt is an integer variable large enough to hold a
1722 pointer.
1724 Pointer arithmetic is valid with Cray pointers, but it is not the same
1725 as C pointer arithmetic.  Cray pointers are just ordinary integers, so
1726 the user is responsible for determining how many bytes to add to a
1727 pointer in order to increment it.  Consider the following example:
1728 @smallexample
1729         real target(10)
1730         real pointee(10)
1731         pointer (ipt, pointee)
1732         ipt = loc (target)
1733         ipt = ipt + 1       
1734 @end smallexample
1735 The last statement does not set @code{ipt} to the address of
1736 @code{target(1)}, as it would in C pointer arithmetic.  Adding @code{1}
1737 to @code{ipt} just adds one byte to the address stored in @code{ipt}.
1739 Any expression involving the pointee will be translated to use the
1740 value stored in the pointer as the base address.
1742 To get the address of elements, this extension provides an intrinsic
1743 function @code{LOC()}.  The @code{LOC()} function is equivalent to the
1744 @code{&} operator in C, except the address is cast to an integer type:
1745 @smallexample
1746         real ar(10)
1747         pointer(ipt, arpte(10))
1748         real arpte
1749         ipt = loc(ar)  ! Makes arpte is an alias for ar
1750         arpte(1) = 1.0 ! Sets ar(1) to 1.0
1751 @end smallexample
1752 The pointer can also be set by a call to the @code{MALLOC} intrinsic
1753 (see @ref{MALLOC}).
1755 Cray pointees often are used to alias an existing variable.  For
1756 example:
1757 @smallexample
1758         integer target(10)
1759         integer iarr(10)
1760         pointer (ipt, iarr)
1761         ipt = loc(target)
1762 @end smallexample
1763 As long as @code{ipt} remains unchanged, @code{iarr} is now an alias for
1764 @code{target}.  The optimizer, however, will not detect this aliasing, so
1765 it is unsafe to use @code{iarr} and @code{target} simultaneously.  Using
1766 a pointee in any way that violates the Fortran aliasing rules or
1767 assumptions is illegal.  It is the user's responsibility to avoid doing
1768 this; the compiler works under the assumption that no such aliasing
1769 occurs.
1771 Cray pointers will work correctly when there is no aliasing (i.e., when
1772 they are used to access a dynamically allocated block of memory), and
1773 also in any routine where a pointee is used, but any variable with which
1774 it shares storage is not used.  Code that violates these rules may not
1775 run as the user intends.  This is not a bug in the optimizer; any code
1776 that violates the aliasing rules is illegal.  (Note that this is not
1777 unique to GNU Fortran; any Fortran compiler that supports Cray pointers
1778 will ``incorrectly'' optimize code with illegal aliasing.)
1780 There are a number of restrictions on the attributes that can be applied
1781 to Cray pointers and pointees.  Pointees may not have the
1782 @code{ALLOCATABLE}, @code{INTENT}, @code{OPTIONAL}, @code{DUMMY},
1783 @code{TARGET}, @code{INTRINSIC}, or @code{POINTER} attributes.  Pointers
1784 may not have the @code{DIMENSION}, @code{POINTER}, @code{TARGET},
1785 @code{ALLOCATABLE}, @code{EXTERNAL}, or @code{INTRINSIC} attributes, nor
1786 may they be function results.  Pointees may not occur in more than one
1787 pointer statement.  A pointee cannot be a pointer.  Pointees cannot occur
1788 in equivalence, common, or data statements.
1790 A Cray pointer may also point to a function or a subroutine.  For
1791 example, the following excerpt is valid:
1792 @smallexample
1793   implicit none
1794   external sub
1795   pointer (subptr,subpte)
1796   external subpte
1797   subptr = loc(sub)
1798   call subpte()
1799   [...]
1800   subroutine sub
1801   [...]
1802   end subroutine sub
1803 @end smallexample
1805 A pointer may be modified during the course of a program, and this
1806 will change the location to which the pointee refers.  However, when
1807 pointees are passed as arguments, they are treated as ordinary
1808 variables in the invoked function.  Subsequent changes to the pointer
1809 will not change the base address of the array that was passed.
1811 @node CONVERT specifier
1812 @subsection @code{CONVERT} specifier
1813 @cindex @code{CONVERT} specifier
1815 GNU Fortran allows the conversion of unformatted data between little-
1816 and big-endian representation to facilitate moving of data
1817 between different systems.  The conversion can be indicated with
1818 the @code{CONVERT} specifier on the @code{OPEN} statement.
1819 @xref{GFORTRAN_CONVERT_UNIT}, for an alternative way of specifying
1820 the data format via an environment variable.
1822 Valid values for @code{CONVERT} are:
1823 @itemize @w{}
1824 @item @code{CONVERT='NATIVE'} Use the native format.  This is the default.
1825 @item @code{CONVERT='SWAP'} Swap between little- and big-endian.
1826 @item @code{CONVERT='LITTLE_ENDIAN'} Use the little-endian representation
1827 for unformatted files.
1828 @item @code{CONVERT='BIG_ENDIAN'} Use the big-endian representation for
1829 unformatted files.
1830 @end itemize
1832 Using the option could look like this:
1833 @smallexample
1834   open(file='big.dat',form='unformatted',access='sequential', &
1835        convert='big_endian')
1836 @end smallexample
1838 The value of the conversion can be queried by using
1839 @code{INQUIRE(CONVERT=ch)}.  The values returned are
1840 @code{'BIG_ENDIAN'} and @code{'LITTLE_ENDIAN'}.
1842 @code{CONVERT} works between big- and little-endian for
1843 @code{INTEGER} values of all supported kinds and for @code{REAL}
1844 on IEEE systems of kinds 4 and 8.  Conversion between different
1845 ``extended double'' types on different architectures such as
1846 m68k and x86_64, which GNU Fortran
1847 supports as @code{REAL(KIND=10)} and @code{REAL(KIND=16)}, will
1848 probably not work.
1850 @emph{Note that the values specified via the GFORTRAN_CONVERT_UNIT
1851 environment variable will override the CONVERT specifier in the
1852 open statement}.  This is to give control over data formats to
1853 users who do not have the source code of their program available.
1855 Using anything but the native representation for unformatted data
1856 carries a significant speed overhead.  If speed in this area matters
1857 to you, it is best if you use this only for data that needs to be
1858 portable.
1860 @node OpenMP
1861 @subsection OpenMP
1862 @cindex OpenMP
1864 OpenMP (Open Multi-Processing) is an application programming
1865 interface (API) that supports multi-platform shared memory 
1866 multiprocessing programming in C/C++ and Fortran on many 
1867 architectures, including Unix and Microsoft Windows platforms.
1868 It consists of a set of compiler directives, library routines,
1869 and environment variables that influence run-time behavior.
1871 GNU Fortran strives to be compatible to the 
1872 @uref{http://www.openmp.org/mp-documents/spec31.pdf,
1873 OpenMP Application Program Interface v3.1}.
1875 To enable the processing of the OpenMP directive @code{!$omp} in
1876 free-form source code; the @code{c$omp}, @code{*$omp} and @code{!$omp}
1877 directives in fixed form; the @code{!$} conditional compilation sentinels
1878 in free form; and the @code{c$}, @code{*$} and @code{!$} sentinels
1879 in fixed form, @command{gfortran} needs to be invoked with the
1880 @option{-fopenmp}.  This also arranges for automatic linking of the
1881 GNU OpenMP runtime library @ref{Top,,libgomp,libgomp,GNU OpenMP
1882 runtime library}.
1884 The OpenMP Fortran runtime library routines are provided both in a
1885 form of a Fortran 90 module named @code{omp_lib} and in a form of
1886 a Fortran @code{include} file named @file{omp_lib.h}.
1888 An example of a parallelized loop taken from Appendix A.1 of
1889 the OpenMP Application Program Interface v2.5:
1890 @smallexample
1891 SUBROUTINE A1(N, A, B)
1892   INTEGER I, N
1893   REAL B(N), A(N)
1894 !$OMP PARALLEL DO !I is private by default
1895   DO I=2,N
1896     B(I) = (A(I) + A(I-1)) / 2.0
1897   ENDDO
1898 !$OMP END PARALLEL DO
1899 END SUBROUTINE A1
1900 @end smallexample
1902 Please note:
1903 @itemize
1904 @item
1905 @option{-fopenmp} implies @option{-frecursive}, i.e., all local arrays
1906 will be allocated on the stack.  When porting existing code to OpenMP,
1907 this may lead to surprising results, especially to segmentation faults
1908 if the stacksize is limited.
1910 @item
1911 On glibc-based systems, OpenMP enabled applications cannot be statically
1912 linked due to limitations of the underlying pthreads-implementation.  It
1913 might be possible to get a working solution if 
1914 @command{-Wl,--whole-archive -lpthread -Wl,--no-whole-archive} is added
1915 to the command line.  However, this is not supported by @command{gcc} and
1916 thus not recommended.
1917 @end itemize
1919 @node Argument list functions
1920 @subsection Argument list functions @code{%VAL}, @code{%REF} and @code{%LOC}
1921 @cindex argument list functions
1922 @cindex @code{%VAL}
1923 @cindex @code{%REF}
1924 @cindex @code{%LOC}
1926 GNU Fortran supports argument list functions @code{%VAL}, @code{%REF} 
1927 and @code{%LOC} statements, for backward compatibility with g77. 
1928 It is recommended that these should be used only for code that is 
1929 accessing facilities outside of GNU Fortran, such as operating system 
1930 or windowing facilities.  It is best to constrain such uses to isolated 
1931 portions of a program--portions that deal specifically and exclusively 
1932 with low-level, system-dependent facilities.  Such portions might well 
1933 provide a portable interface for use by the program as a whole, but are 
1934 themselves not portable, and should be thoroughly tested each time they 
1935 are rebuilt using a new compiler or version of a compiler.
1937 @code{%VAL} passes a scalar argument by value, @code{%REF} passes it by 
1938 reference and @code{%LOC} passes its memory location.  Since gfortran 
1939 already passes scalar arguments by reference, @code{%REF} is in effect 
1940 a do-nothing.  @code{%LOC} has the same effect as a Fortran pointer.
1942 An example of passing an argument by value to a C subroutine foo.:
1943 @smallexample
1945 C prototype      void foo_ (float x);
1947       external foo
1948       real*4 x
1949       x = 3.14159
1950       call foo (%VAL (x))
1951       end
1952 @end smallexample
1954 For details refer to the g77 manual
1955 @uref{http://gcc.gnu.org/@/onlinedocs/@/gcc-3.4.6/@/g77/@/index.html#Top}.
1957 Also, @code{c_by_val.f} and its partner @code{c_by_val.c} of the
1958 GNU Fortran testsuite are worth a look.
1961 @node Extensions not implemented in GNU Fortran
1962 @section Extensions not implemented in GNU Fortran
1963 @cindex extensions, not implemented
1965 The long history of the Fortran language, its wide use and broad
1966 userbase, the large number of different compiler vendors and the lack of
1967 some features crucial to users in the first standards have lead to the
1968 existence of a number of important extensions to the language.  While
1969 some of the most useful or popular extensions are supported by the GNU
1970 Fortran compiler, not all existing extensions are supported.  This section
1971 aims at listing these extensions and offering advice on how best make
1972 code that uses them running with the GNU Fortran compiler.
1974 @c More can be found here:
1975 @c   -- http://gcc.gnu.org/onlinedocs/gcc-3.4.6/g77/Missing-Features.html
1976 @c   -- the list of Fortran and libgfortran bugs closed as WONTFIX:
1977 @c      http://tinyurl.com/2u4h5y
1979 @menu
1980 * STRUCTURE and RECORD::
1981 @c * UNION and MAP::
1982 * ENCODE and DECODE statements::
1983 * Variable FORMAT expressions::
1984 @c * Q edit descriptor::
1985 @c * AUTOMATIC statement::
1986 @c * TYPE and ACCEPT I/O Statements::
1987 @c * .XOR. operator::
1988 @c * CARRIAGECONTROL, DEFAULTFILE, DISPOSE and RECORDTYPE I/O specifiers::
1989 @c * Omitted arguments in procedure call::
1990 * Alternate complex function syntax::
1991 @end menu
1994 @node STRUCTURE and RECORD
1995 @subsection @code{STRUCTURE} and @code{RECORD}
1996 @cindex @code{STRUCTURE}
1997 @cindex @code{RECORD}
1999 Record structures are a pre-Fortran-90 vendor extension to create
2000 user-defined aggregate data types.  GNU Fortran does not support
2001 record structures, only Fortran 90's ``derived types'', which have
2002 a different syntax.
2004 In many cases, record structures can easily be converted to derived types.
2005 To convert, replace @code{STRUCTURE /}@var{structure-name}@code{/}
2006 by @code{TYPE} @var{type-name}.  Additionally, replace
2007 @code{RECORD /}@var{structure-name}@code{/} by
2008 @code{TYPE(}@var{type-name}@code{)}. Finally, in the component access,
2009 replace the period (@code{.}) by the percent sign (@code{%}).
2011 Here is an example of code using the non portable record structure syntax:
2013 @example
2014 ! Declaring a structure named ``item'' and containing three fields:
2015 ! an integer ID, an description string and a floating-point price.
2016 STRUCTURE /item/
2017   INTEGER id
2018   CHARACTER(LEN=200) description
2019   REAL price
2020 END STRUCTURE
2022 ! Define two variables, an single record of type ``item''
2023 ! named ``pear'', and an array of items named ``store_catalog''
2024 RECORD /item/ pear, store_catalog(100)
2026 ! We can directly access the fields of both variables
2027 pear.id = 92316
2028 pear.description = "juicy D'Anjou pear"
2029 pear.price = 0.15
2030 store_catalog(7).id = 7831
2031 store_catalog(7).description = "milk bottle"
2032 store_catalog(7).price = 1.2
2034 ! We can also manipulate the whole structure
2035 store_catalog(12) = pear
2036 print *, store_catalog(12)
2037 @end example
2039 @noindent
2040 This code can easily be rewritten in the Fortran 90 syntax as following:
2042 @example
2043 ! ``STRUCTURE /name/ ... END STRUCTURE'' becomes
2044 ! ``TYPE name ... END TYPE''
2045 TYPE item
2046   INTEGER id
2047   CHARACTER(LEN=200) description
2048   REAL price
2049 END TYPE
2051 ! ``RECORD /name/ variable'' becomes ``TYPE(name) variable''
2052 TYPE(item) pear, store_catalog(100)
2054 ! Instead of using a dot (.) to access fields of a record, the
2055 ! standard syntax uses a percent sign (%)
2056 pear%id = 92316
2057 pear%description = "juicy D'Anjou pear"
2058 pear%price = 0.15
2059 store_catalog(7)%id = 7831
2060 store_catalog(7)%description = "milk bottle"
2061 store_catalog(7)%price = 1.2
2063 ! Assignments of a whole variable do not change
2064 store_catalog(12) = pear
2065 print *, store_catalog(12)
2066 @end example
2069 @c @node UNION and MAP
2070 @c @subsection @code{UNION} and @code{MAP}
2071 @c @cindex @code{UNION}
2072 @c @cindex @code{MAP}
2074 @c For help writing this one, see
2075 @c http://www.eng.umd.edu/~nsw/ench250/fortran1.htm#UNION and
2076 @c http://www.tacc.utexas.edu/services/userguides/pgi/pgiws_ug/pgi32u06.htm
2079 @node ENCODE and DECODE statements
2080 @subsection @code{ENCODE} and @code{DECODE} statements
2081 @cindex @code{ENCODE}
2082 @cindex @code{DECODE}
2084 GNU Fortran does not support the @code{ENCODE} and @code{DECODE}
2085 statements.  These statements are best replaced by @code{READ} and
2086 @code{WRITE} statements involving internal files (@code{CHARACTER}
2087 variables and arrays), which have been part of the Fortran standard since
2088 Fortran 77.  For example, replace a code fragment like
2090 @smallexample
2091       INTEGER*1 LINE(80)
2092       REAL A, B, C
2093 c     ... Code that sets LINE
2094       DECODE (80, 9000, LINE) A, B, C
2095  9000 FORMAT (1X, 3(F10.5))
2096 @end smallexample
2098 @noindent
2099 with the following:
2101 @smallexample
2102       CHARACTER(LEN=80) LINE
2103       REAL A, B, C
2104 c     ... Code that sets LINE
2105       READ (UNIT=LINE, FMT=9000) A, B, C
2106  9000 FORMAT (1X, 3(F10.5))
2107 @end smallexample
2109 Similarly, replace a code fragment like
2111 @smallexample
2112       INTEGER*1 LINE(80)
2113       REAL A, B, C
2114 c     ... Code that sets A, B and C
2115       ENCODE (80, 9000, LINE) A, B, C
2116  9000 FORMAT (1X, 'OUTPUT IS ', 3(F10.5))
2117 @end smallexample
2119 @noindent
2120 with the following:
2122 @smallexample
2123       CHARACTER(LEN=80) LINE
2124       REAL A, B, C
2125 c     ... Code that sets A, B and C
2126       WRITE (UNIT=LINE, FMT=9000) A, B, C
2127  9000 FORMAT (1X, 'OUTPUT IS ', 3(F10.5))
2128 @end smallexample
2131 @node Variable FORMAT expressions
2132 @subsection Variable @code{FORMAT} expressions
2133 @cindex @code{FORMAT}
2135 A variable @code{FORMAT} expression is format statement which includes
2136 angle brackets enclosing a Fortran expression: @code{FORMAT(I<N>)}.  GNU
2137 Fortran does not support this legacy extension.  The effect of variable
2138 format expressions can be reproduced by using the more powerful (and
2139 standard) combination of internal output and string formats.  For example,
2140 replace a code fragment like this:
2142 @smallexample
2143       WRITE(6,20) INT1
2144  20   FORMAT(I<N+1>)
2145 @end smallexample
2147 @noindent
2148 with the following:
2150 @smallexample
2151 c     Variable declaration
2152       CHARACTER(LEN=20) FMT
2153 c     
2154 c     Other code here...
2156       WRITE(FMT,'("(I", I0, ")")') N+1
2157       WRITE(6,FMT) INT1
2158 @end smallexample
2160 @noindent
2161 or with:
2163 @smallexample
2164 c     Variable declaration
2165       CHARACTER(LEN=20) FMT
2166 c     
2167 c     Other code here...
2169       WRITE(FMT,*) N+1
2170       WRITE(6,"(I" // ADJUSTL(FMT) // ")") INT1
2171 @end smallexample
2174 @node Alternate complex function syntax
2175 @subsection Alternate complex function syntax
2176 @cindex Complex function
2178 Some Fortran compilers, including @command{g77}, let the user declare
2179 complex functions with the syntax @code{COMPLEX FUNCTION name*16()}, as
2180 well as @code{COMPLEX*16 FUNCTION name()}.  Both are non-standard, legacy
2181 extensions.  @command{gfortran} accepts the latter form, which is more
2182 common, but not the former.
2186 @c ---------------------------------------------------------------------
2187 @c Mixed-Language Programming
2188 @c ---------------------------------------------------------------------
2190 @node Mixed-Language Programming
2191 @chapter Mixed-Language Programming
2192 @cindex Interoperability
2193 @cindex Mixed-language programming
2195 @menu
2196 * Interoperability with C::
2197 * GNU Fortran Compiler Directives::
2198 * Non-Fortran Main Program::
2199 * Naming and argument-passing conventions::
2200 @end menu
2202 This chapter is about mixed-language interoperability, but also applies
2203 if one links Fortran code compiled by different compilers.  In most cases,
2204 use of the C Binding features of the Fortran 2003 standard is sufficient,
2205 and their use is highly recommended.
2208 @node Interoperability with C
2209 @section Interoperability with C
2211 @menu
2212 * Intrinsic Types::
2213 * Derived Types and struct::
2214 * Interoperable Global Variables::
2215 * Interoperable Subroutines and Functions::
2216 * Working with Pointers::
2217 * Further Interoperability of Fortran with C::
2218 @end menu
2220 Since Fortran 2003 (ISO/IEC 1539-1:2004(E)) there is a
2221 standardized way to generate procedure and derived-type
2222 declarations and global variables which are interoperable with C
2223 (ISO/IEC 9899:1999).  The @code{bind(C)} attribute has been added
2224 to inform the compiler that a symbol shall be interoperable with C;
2225 also, some constraints are added.  Note, however, that not
2226 all C features have a Fortran equivalent or vice versa.  For instance,
2227 neither C's unsigned integers nor C's functions with variable number
2228 of arguments have an equivalent in Fortran.
2230 Note that array dimensions are reversely ordered in C and that arrays in
2231 C always start with index 0 while in Fortran they start by default with
2232 1.  Thus, an array declaration @code{A(n,m)} in Fortran matches
2233 @code{A[m][n]} in C and accessing the element @code{A(i,j)} matches
2234 @code{A[j-1][i-1]}.  The element following @code{A(i,j)} (C: @code{A[j-1][i-1]};
2235 assuming @math{i < n}) in memory is @code{A(i+1,j)} (C: @code{A[j-1][i]}).
2237 @node Intrinsic Types
2238 @subsection Intrinsic Types
2240 In order to ensure that exactly the same variable type and kind is used
2241 in C and Fortran, the named constants shall be used which are defined in the
2242 @code{ISO_C_BINDING} intrinsic module.  That module contains named constants
2243 for kind parameters and character named constants for the escape sequences
2244 in C.  For a list of the constants, see @ref{ISO_C_BINDING}.
2246 For logical types, please note that the Fortran standard only guarantees
2247 interoperability between C99's @code{_Bool} and Fortran's @code{C_Bool}-kind
2248 logicals and C99 defines that @code{true} has the value 1 and @code{false}
2249 the value 0.  Using any other integer value with GNU Fortran's @code{LOGICAL}
2250 (with any kind parameter) gives an undefined result.  (Passing other integer
2251 values than 0 and 1 to GCC's @code{_Bool} is also undefined, unless the
2252 integer is explicitly or implicitly casted to @code{_Bool}.)
2256 @node Derived Types and struct
2257 @subsection Derived Types and struct
2259 For compatibility of derived types with @code{struct}, one needs to use
2260 the @code{BIND(C)} attribute in the type declaration.  For instance, the
2261 following type declaration
2263 @smallexample
2264  USE ISO_C_BINDING
2265  TYPE, BIND(C) :: myType
2266    INTEGER(C_INT) :: i1, i2
2267    INTEGER(C_SIGNED_CHAR) :: i3
2268    REAL(C_DOUBLE) :: d1
2269    COMPLEX(C_FLOAT_COMPLEX) :: c1
2270    CHARACTER(KIND=C_CHAR) :: str(5)
2271  END TYPE
2272 @end smallexample
2274 matches the following @code{struct} declaration in C
2276 @smallexample
2277  struct @{
2278    int i1, i2;
2279    /* Note: "char" might be signed or unsigned.  */
2280    signed char i3;
2281    double d1;
2282    float _Complex c1;
2283    char str[5];
2284  @} myType;
2285 @end smallexample
2287 Derived types with the C binding attribute shall not have the @code{sequence}
2288 attribute, type parameters, the @code{extends} attribute, nor type-bound
2289 procedures.  Every component must be of interoperable type and kind and may not
2290 have the @code{pointer} or @code{allocatable} attribute.  The names of the
2291 components are irrelevant for interoperability.
2293 As there exist no direct Fortran equivalents, neither unions nor structs
2294 with bit field or variable-length array members are interoperable.
2296 @node Interoperable Global Variables
2297 @subsection Interoperable Global Variables
2299 Variables can be made accessible from C using the C binding attribute,
2300 optionally together with specifying a binding name.  Those variables
2301 have to be declared in the declaration part of a @code{MODULE},
2302 be of interoperable type, and have neither the @code{pointer} nor
2303 the @code{allocatable} attribute.
2305 @smallexample
2306   MODULE m
2307     USE myType_module
2308     USE ISO_C_BINDING
2309     integer(C_INT), bind(C, name="_MyProject_flags") :: global_flag
2310     type(myType), bind(C) :: tp
2311   END MODULE
2312 @end smallexample
2314 Here, @code{_MyProject_flags} is the case-sensitive name of the variable
2315 as seen from C programs while @code{global_flag} is the case-insensitive
2316 name as seen from Fortran.  If no binding name is specified, as for
2317 @var{tp}, the C binding name is the (lowercase) Fortran binding name.
2318 If a binding name is specified, only a single variable may be after the
2319 double colon.  Note of warning: You cannot use a global variable to
2320 access @var{errno} of the C library as the C standard allows it to be
2321 a macro.  Use the @code{IERRNO} intrinsic (GNU extension) instead.
2323 @node Interoperable Subroutines and Functions
2324 @subsection Interoperable Subroutines and Functions
2326 Subroutines and functions have to have the @code{BIND(C)} attribute to
2327 be compatible with C.  The dummy argument declaration is relatively
2328 straightforward.  However, one needs to be careful because C uses
2329 call-by-value by default while Fortran behaves usually similar to
2330 call-by-reference.  Furthermore, strings and pointers are handled
2331 differently.  Note that in Fortran 2003 and 2008 only explicit size
2332 and assumed-size arrays are supported but not assumed-shape or
2333 deferred-shape (i.e. allocatable or pointer) arrays.  However, those
2334 are allowed since the Technical Specification 29113, see
2335 @ref{Further Interoperability of Fortran with C}
2337 To pass a variable by value, use the @code{VALUE} attribute.
2338 Thus, the following C prototype
2340 @smallexample
2341 @code{int func(int i, int *j)}
2342 @end smallexample
2344 matches the Fortran declaration
2346 @smallexample
2347   integer(c_int) function func(i,j)
2348     use iso_c_binding, only: c_int
2349     integer(c_int), VALUE :: i
2350     integer(c_int) :: j
2351 @end smallexample
2353 Note that pointer arguments also frequently need the @code{VALUE} attribute,
2354 see @ref{Working with Pointers}.
2356 Strings are handled quite differently in C and Fortran.  In C a string
2357 is a @code{NUL}-terminated array of characters while in Fortran each string
2358 has a length associated with it and is thus not terminated (by e.g.
2359 @code{NUL}).  For example, if one wants to use the following C function,
2361 @smallexample
2362   #include <stdio.h>
2363   void print_C(char *string) /* equivalent: char string[]  */
2364   @{
2365      printf("%s\n", string);
2366   @}
2367 @end smallexample
2369 to print ``Hello World'' from Fortran, one can call it using
2371 @smallexample
2372   use iso_c_binding, only: C_CHAR, C_NULL_CHAR
2373   interface
2374     subroutine print_c(string) bind(C, name="print_C")
2375       use iso_c_binding, only: c_char
2376       character(kind=c_char) :: string(*)
2377     end subroutine print_c
2378   end interface
2379   call print_c(C_CHAR_"Hello World"//C_NULL_CHAR)
2380 @end smallexample
2382 As the example shows, one needs to ensure that the
2383 string is @code{NUL} terminated.  Additionally, the dummy argument
2384 @var{string} of @code{print_C} is a length-one assumed-size
2385 array; using @code{character(len=*)} is not allowed.  The example
2386 above uses @code{c_char_"Hello World"} to ensure the string
2387 literal has the right type; typically the default character
2388 kind and @code{c_char} are the same and thus @code{"Hello World"}
2389 is equivalent.  However, the standard does not guarantee this.
2391 The use of strings is now further illustrated using the C library
2392 function @code{strncpy}, whose prototype is
2394 @smallexample
2395   char *strncpy(char *restrict s1, const char *restrict s2, size_t n);
2396 @end smallexample
2398 The function @code{strncpy} copies at most @var{n} characters from
2399 string @var{s2} to @var{s1} and returns @var{s1}.  In the following
2400 example, we ignore the return value:
2402 @smallexample
2403   use iso_c_binding
2404   implicit none
2405   character(len=30) :: str,str2
2406   interface
2407     ! Ignore the return value of strncpy -> subroutine
2408     ! "restrict" is always assumed if we do not pass a pointer
2409     subroutine strncpy(dest, src, n) bind(C)
2410       import
2411       character(kind=c_char),  intent(out) :: dest(*)
2412       character(kind=c_char),  intent(in)  :: src(*)
2413       integer(c_size_t), value, intent(in) :: n
2414     end subroutine strncpy
2415   end interface
2416   str = repeat('X',30) ! Initialize whole string with 'X'
2417   call strncpy(str, c_char_"Hello World"//C_NULL_CHAR, &
2418                len(c_char_"Hello World",kind=c_size_t))
2419   print '(a)', str ! prints: "Hello WorldXXXXXXXXXXXXXXXXXXX"
2420   end
2421 @end smallexample
2423 The intrinsic procedures are described in @ref{Intrinsic Procedures}.
2425 @node Working with Pointers
2426 @subsection Working with Pointers
2428 C pointers are represented in Fortran via the special opaque derived type
2429 @code{type(c_ptr)} (with private components).  Thus one needs to
2430 use intrinsic conversion procedures to convert from or to C pointers.
2432 For some applications, using an assumed type (@code{TYPE(*)}) can be an
2433 alternative to a C pointer; see
2434 @ref{Further Interoperability of Fortran with C}.
2436 For example,
2438 @smallexample
2439   use iso_c_binding
2440   type(c_ptr) :: cptr1, cptr2
2441   integer, target :: array(7), scalar
2442   integer, pointer :: pa(:), ps
2443   cptr1 = c_loc(array(1)) ! The programmer needs to ensure that the
2444                           ! array is contiguous if required by the C
2445                           ! procedure
2446   cptr2 = c_loc(scalar)
2447   call c_f_pointer(cptr2, ps)
2448   call c_f_pointer(cptr2, pa, shape=[7])
2449 @end smallexample
2451 When converting C to Fortran arrays, the one-dimensional @code{SHAPE} argument
2452 has to be passed.
2454 If a pointer is a dummy-argument of an interoperable procedure, it usually
2455 has to be declared using the @code{VALUE} attribute.  @code{void*}
2456 matches @code{TYPE(C_PTR), VALUE}, while @code{TYPE(C_PTR)} alone
2457 matches @code{void**}.
2459 Procedure pointers are handled analogously to pointers; the C type is
2460 @code{TYPE(C_FUNPTR)} and the intrinsic conversion procedures are
2461 @code{C_F_PROCPOINTER} and @code{C_FUNLOC}.
2463 Let us consider two examples of actually passing a procedure pointer from
2464 C to Fortran and vice versa.  Note that these examples are also very
2465 similar to passing ordinary pointers between both languages. First,
2466 consider this code in C:
2468 @smallexample
2469 /* Procedure implemented in Fortran.  */
2470 void get_values (void (*)(double));
2472 /* Call-back routine we want called from Fortran.  */
2473 void
2474 print_it (double x)
2476   printf ("Number is %f.\n", x);
2479 /* Call Fortran routine and pass call-back to it.  */
2480 void
2481 foobar ()
2483   get_values (&print_it);
2485 @end smallexample
2487 A matching implementation for @code{get_values} in Fortran, that correctly
2488 receives the procedure pointer from C and is able to call it, is given
2489 in the following @code{MODULE}:
2491 @smallexample
2492 MODULE m
2493   IMPLICIT NONE
2495   ! Define interface of call-back routine.
2496   ABSTRACT INTERFACE
2497     SUBROUTINE callback (x)
2498       USE, INTRINSIC :: ISO_C_BINDING
2499       REAL(KIND=C_DOUBLE), INTENT(IN), VALUE :: x
2500     END SUBROUTINE callback
2501   END INTERFACE
2503 CONTAINS
2505   ! Define C-bound procedure.
2506   SUBROUTINE get_values (cproc) BIND(C)
2507     USE, INTRINSIC :: ISO_C_BINDING
2508     TYPE(C_FUNPTR), INTENT(IN), VALUE :: cproc
2510     PROCEDURE(callback), POINTER :: proc
2512     ! Convert C to Fortran procedure pointer.
2513     CALL C_F_PROCPOINTER (cproc, proc)
2515     ! Call it.
2516     CALL proc (1.0_C_DOUBLE)
2517     CALL proc (-42.0_C_DOUBLE)
2518     CALL proc (18.12_C_DOUBLE)
2519   END SUBROUTINE get_values
2521 END MODULE m
2522 @end smallexample
2524 Next, we want to call a C routine that expects a procedure pointer argument
2525 and pass it a Fortran procedure (which clearly must be interoperable!).
2526 Again, the C function may be:
2528 @smallexample
2530 call_it (int (*func)(int), int arg)
2532   return func (arg);
2534 @end smallexample
2536 It can be used as in the following Fortran code:
2538 @smallexample
2539 MODULE m
2540   USE, INTRINSIC :: ISO_C_BINDING
2541   IMPLICIT NONE
2543   ! Define interface of C function.
2544   INTERFACE
2545     INTEGER(KIND=C_INT) FUNCTION call_it (func, arg) BIND(C)
2546       USE, INTRINSIC :: ISO_C_BINDING
2547       TYPE(C_FUNPTR), INTENT(IN), VALUE :: func
2548       INTEGER(KIND=C_INT), INTENT(IN), VALUE :: arg
2549     END FUNCTION call_it
2550   END INTERFACE
2552 CONTAINS
2554   ! Define procedure passed to C function.
2555   ! It must be interoperable!
2556   INTEGER(KIND=C_INT) FUNCTION double_it (arg) BIND(C)
2557     INTEGER(KIND=C_INT), INTENT(IN), VALUE :: arg
2558     double_it = arg + arg
2559   END FUNCTION double_it
2561   ! Call C function.
2562   SUBROUTINE foobar ()
2563     TYPE(C_FUNPTR) :: cproc
2564     INTEGER(KIND=C_INT) :: i
2566     ! Get C procedure pointer.
2567     cproc = C_FUNLOC (double_it)
2569     ! Use it.
2570     DO i = 1_C_INT, 10_C_INT
2571       PRINT *, call_it (cproc, i)
2572     END DO
2573   END SUBROUTINE foobar
2575 END MODULE m
2576 @end smallexample
2578 @node Further Interoperability of Fortran with C
2579 @subsection Further Interoperability of Fortran with C
2581 The Technical Specification ISO/IEC TS 29113:2012 on further
2582 interoperability of Fortran with C extends the interoperability support
2583 of Fortran 2003 and Fortran 2008. Besides removing some restrictions
2584 and constraints, it adds assumed-type (@code{TYPE(*)}) and assumed-rank
2585 (@code{dimension}) variables and allows for interoperability of
2586 assumed-shape, assumed-rank and deferred-shape arrays, including
2587 allocatables and pointers.
2589 Note: Currently, GNU Fortran does not support the array descriptor
2590 (dope vector) as specified in the Technical Specification, but uses
2591 an array descriptor with different fields. The Chasm Language
2592 Interoperability Tools, @url{http://chasm-interop.sourceforge.net/},
2593 provide an interface to GNU Fortran's array descriptor.
2595 The Technical Specification adds the following new features, which
2596 are supported by GNU Fortran:
2598 @itemize @bullet
2600 @item The @code{ASYNCHRONOUS} attribute has been clarified and
2601 extended to allow its use with asynchronous communication in
2602 user-provided libraries such as in implementations of the
2603 Message Passing Interface specification.
2605 @item Many constraints have been relaxed, in particular for
2606 the @code{C_LOC} and @code{C_F_POINTER} intrinsics.
2608 @item The @code{OPTIONAL} attribute is now allowed for dummy
2609 arguments; an absent argument matches a @code{NULL} pointer.
2611 @item Assumed types (@code{TYPE(*)}) have been added, which may
2612 only be used for dummy arguments.  They are unlimited polymorphic
2613 but contrary to @code{CLASS(*)} they do not contain any type
2614 information, similar to C's @code{void *} pointers.  Expressions
2615 of any type and kind can be passed; thus, it can be used as
2616 replacement for @code{TYPE(C_PTR)}, avoiding the use of
2617 @code{C_LOC} in the caller.
2619 Note, however, that @code{TYPE(*)} only accepts scalar arguments,
2620 unless the @code{DIMENSION} is explicitly specified.  As
2621 @code{DIMENSION(*)} only supports array (including array elements) but
2622 no scalars, it is not a full replacement for @code{C_LOC}.  On the
2623 other hand, assumed-type assumed-rank dummy arguments
2624 (@code{TYPE(*), DIMENSION(..)}) allow for both scalars and arrays, but
2625 require special code on the callee side to handle the array descriptor.
2627 @item Assumed-rank arrays (@code{DIMENSION(..)}) as dummy argument
2628 allow that scalars and arrays of any rank can be passed as actual
2629 argument. As the Technical Specification does not provide for direct
2630 means to operate with them, they have to be used either from the C side
2631 or be converted using @code{C_LOC} and @code{C_F_POINTER} to scalars
2632 or arrays of a specific rank. The rank can be determined using the
2633 @code{RANK} intrinisic.
2634 @end itemize
2637 Currently unimplemented:
2639 @itemize @bullet
2641 @item GNU Fortran always uses an array descriptor, which does not
2642 match the one of the Technical Specification. The
2643 @code{ISO_Fortran_binding.h} header file and the C functions it
2644 specifies are not available.
2646 @item Using assumed-shape, assumed-rank and deferred-shape arrays in
2647 @code{BIND(C)} procedures is not fully supported. In particular,
2648 C interoperable strings of other length than one are not supported
2649 as this requires the new array descriptor.
2650 @end itemize
2653 @node GNU Fortran Compiler Directives
2654 @section GNU Fortran Compiler Directives
2656 The Fortran standard describes how a conforming program shall
2657 behave; however, the exact implementation is not standardized.  In order
2658 to allow the user to choose specific implementation details, compiler
2659 directives can be used to set attributes of variables and procedures
2660 which are not part of the standard.  Whether a given attribute is
2661 supported and its exact effects depend on both the operating system and
2662 on the processor; see
2663 @ref{Top,,C Extensions,gcc,Using the GNU Compiler Collection (GCC)}
2664 for details.
2666 For procedures and procedure pointers, the following attributes can
2667 be used to change the calling convention:
2669 @itemize
2670 @item @code{CDECL} -- standard C calling convention
2671 @item @code{STDCALL} -- convention where the called procedure pops the stack
2672 @item @code{FASTCALL} -- part of the arguments are passed via registers
2673 instead using the stack
2674 @end itemize
2676 Besides changing the calling convention, the attributes also influence
2677 the decoration of the symbol name, e.g., by a leading underscore or by
2678 a trailing at-sign followed by the number of bytes on the stack.  When
2679 assigning a procedure to a procedure pointer, both should use the same
2680 calling convention.
2682 On some systems, procedures and global variables (module variables and
2683 @code{COMMON} blocks) need special handling to be accessible when they
2684 are in a shared library.  The following attributes are available:
2686 @itemize
2687 @item @code{DLLEXPORT} -- provide a global pointer to a pointer in the DLL
2688 @item @code{DLLIMPORT} -- reference the function or variable using a global pointer 
2689 @end itemize
2691 For dummy arguments, the @code{NO_ARG_CHECK} attribute can be used; in
2692 other compilers, it is also known as @code{IGNORE_TKR}.  For dummy arguments
2693 with this attribute actual arguments of any type and kind (similar to
2694 @code{TYPE(*)}), scalars and arrays of any rank (no equivalent
2695 in Fortran standard) are accepted.  As with @code{TYPE(*)}, the argument
2696 is unlimited polymorphic and no type information is available.
2697 Additionally, the argument may only be passed to dummy arguments
2698 with the @code{NO_ARG_CHECK} attribute and as argument to the
2699 @code{PRESENT} intrinsic function and to @code{C_LOC} of the
2700 @code{ISO_C_BINDING} module.
2702 Variables with @code{NO_ARG_CHECK} attribute shall be of assumed-type
2703 (@code{TYPE(*)}; recommended) or of type @code{INTEGER}, @code{LOGICAL},
2704 @code{REAL} or @code{COMPLEX}. They shall not have the @code{ALLOCATE},
2705 @code{CODIMENSION}, @code{INTENT(OUT)}, @code{POINTER} or @code{VALUE}
2706 attribute; furthermore, they shall be either scalar or of assumed-size
2707 (@code{dimension(*)}). As @code{TYPE(*)}, the @code{NO_ARG_CHECK} attribute
2708 requires an explicit interface.
2710 @itemize
2711 @item @code{NO_ARG_CHECK} -- disable the type, kind and rank checking
2712 @end itemize
2715 The attributes are specified using the syntax
2717 @code{!GCC$ ATTRIBUTES} @var{attribute-list} @code{::} @var{variable-list}
2719 where in free-form source code only whitespace is allowed before @code{!GCC$}
2720 and in fixed-form source code @code{!GCC$}, @code{cGCC$} or @code{*GCC$} shall
2721 start in the first column.
2723 For procedures, the compiler directives shall be placed into the body
2724 of the procedure; for variables and procedure pointers, they shall be in
2725 the same declaration part as the variable or procedure pointer.
2729 @node Non-Fortran Main Program
2730 @section Non-Fortran Main Program
2732 @menu
2733 * _gfortran_set_args:: Save command-line arguments
2734 * _gfortran_set_options:: Set library option flags
2735 * _gfortran_set_convert:: Set endian conversion
2736 * _gfortran_set_record_marker:: Set length of record markers
2737 * _gfortran_set_fpe:: Set when a Floating Point Exception should be raised
2738 * _gfortran_set_max_subrecord_length:: Set subrecord length
2739 @end menu
2741 Even if you are doing mixed-language programming, it is very
2742 likely that you do not need to know or use the information in this
2743 section.  Since it is about the internal structure of GNU Fortran,
2744 it may also change in GCC minor releases.
2746 When you compile a @code{PROGRAM} with GNU Fortran, a function
2747 with the name @code{main} (in the symbol table of the object file)
2748 is generated, which initializes the libgfortran library and then
2749 calls the actual program which uses the name @code{MAIN__}, for
2750 historic reasons.  If you link GNU Fortran compiled procedures
2751 to, e.g., a C or C++ program or to a Fortran program compiled by
2752 a different compiler, the libgfortran library is not initialized
2753 and thus a few intrinsic procedures do not work properly, e.g.
2754 those for obtaining the command-line arguments.
2756 Therefore, if your @code{PROGRAM} is not compiled with
2757 GNU Fortran and the GNU Fortran compiled procedures require
2758 intrinsics relying on the library initialization, you need to
2759 initialize the library yourself.  Using the default options,
2760 gfortran calls @code{_gfortran_set_args} and
2761 @code{_gfortran_set_options}.  The initialization of the former
2762 is needed if the called procedures access the command line
2763 (and for backtracing); the latter sets some flags based on the
2764 standard chosen or to enable backtracing.  In typical programs,
2765 it is not necessary to call any initialization function.
2767 If your @code{PROGRAM} is compiled with GNU Fortran, you shall
2768 not call any of the following functions.  The libgfortran
2769 initialization functions are shown in C syntax but using C
2770 bindings they are also accessible from Fortran.
2773 @node _gfortran_set_args
2774 @subsection @code{_gfortran_set_args} --- Save command-line arguments
2775 @fnindex _gfortran_set_args
2776 @cindex libgfortran initialization, set_args
2778 @table @asis
2779 @item @emph{Description}:
2780 @code{_gfortran_set_args} saves the command-line arguments; this
2781 initialization is required if any of the command-line intrinsics
2782 is called.  Additionally, it shall be called if backtracing is
2783 enabled (see @code{_gfortran_set_options}).
2785 @item @emph{Syntax}:
2786 @code{void _gfortran_set_args (int argc, char *argv[])}
2788 @item @emph{Arguments}:
2789 @multitable @columnfractions .15 .70
2790 @item @var{argc} @tab number of command line argument strings
2791 @item @var{argv} @tab the command-line argument strings; argv[0]
2792 is the pathname of the executable itself.
2793 @end multitable
2795 @item @emph{Example}:
2796 @smallexample
2797 int main (int argc, char *argv[])
2799   /* Initialize libgfortran.  */
2800   _gfortran_set_args (argc, argv);
2801   return 0;
2803 @end smallexample
2804 @end table
2807 @node _gfortran_set_options
2808 @subsection @code{_gfortran_set_options} --- Set library option flags
2809 @fnindex _gfortran_set_options
2810 @cindex libgfortran initialization, set_options
2812 @table @asis
2813 @item @emph{Description}:
2814 @code{_gfortran_set_options} sets several flags related to the Fortran
2815 standard to be used, whether backtracing should be enabled
2816 and whether range checks should be performed.  The syntax allows for
2817 upward compatibility since the number of passed flags is specified; for
2818 non-passed flags, the default value is used.  See also
2819 @pxref{Code Gen Options}.  Please note that not all flags are actually
2820 used.
2822 @item @emph{Syntax}:
2823 @code{void _gfortran_set_options (int num, int options[])}
2825 @item @emph{Arguments}:
2826 @multitable @columnfractions .15 .70
2827 @item @var{num} @tab number of options passed
2828 @item @var{argv} @tab The list of flag values
2829 @end multitable
2831 @item @emph{option flag list}:
2832 @multitable @columnfractions .15 .70
2833 @item @var{option}[0] @tab Allowed standard; can give run-time errors
2834 if e.g. an input-output edit descriptor is invalid in a given standard.
2835 Possible values are (bitwise or-ed) @code{GFC_STD_F77} (1),
2836 @code{GFC_STD_F95_OBS} (2), @code{GFC_STD_F95_DEL} (4), @code{GFC_STD_F95}
2837 (8), @code{GFC_STD_F2003} (16), @code{GFC_STD_GNU} (32),
2838 @code{GFC_STD_LEGACY} (64), @code{GFC_STD_F2008} (128), 
2839 @code{GFC_STD_F2008_OBS} (256) and GFC_STD_F2008_TS (512). Default:
2840 @code{GFC_STD_F95_OBS | GFC_STD_F95_DEL | GFC_STD_F95 | GFC_STD_F2003
2841 | GFC_STD_F2008 | GFC_STD_F2008_TS | GFC_STD_F2008_OBS | GFC_STD_F77
2842 | GFC_STD_GNU | GFC_STD_LEGACY}.
2843 @item @var{option}[1] @tab Standard-warning flag; prints a warning to
2844 standard error.  Default: @code{GFC_STD_F95_DEL | GFC_STD_LEGACY}.
2845 @item @var{option}[2] @tab If non zero, enable pedantic checking.
2846 Default: off.
2847 @item @var{option}[3] @tab Unused.
2848 @item @var{option}[4] @tab If non zero, enable backtracing on run-time
2849 errors.  Default: off. (Default in the compiler: on.)
2850 Note: Installs a signal handler and requires command-line
2851 initialization using @code{_gfortran_set_args}.
2852 @item @var{option}[5] @tab If non zero, supports signed zeros.
2853 Default: enabled.
2854 @item @var{option}[6] @tab Enables run-time checking.  Possible values
2855 are (bitwise or-ed): GFC_RTCHECK_BOUNDS (1), GFC_RTCHECK_ARRAY_TEMPS (2),
2856 GFC_RTCHECK_RECURSION (4), GFC_RTCHECK_DO (16), GFC_RTCHECK_POINTER (32).
2857 Default: disabled.
2858 @item @var{option}[7] @tab Unused.
2859 @item @var{option}[8] @tab Show a warning when invoking @code{STOP} and
2860 @code{ERROR STOP} if a floating-point exception occurred. Possible values
2861 are (bitwise or-ed) @code{GFC_FPE_INVALID} (1), @code{GFC_FPE_DENORMAL} (2),
2862 @code{GFC_FPE_ZERO} (4), @code{GFC_FPE_OVERFLOW} (8),
2863 @code{GFC_FPE_UNDERFLOW} (16), @code{GFC_FPE_INEXACT} (32). Default: None (0).
2864 (Default in the compiler: @code{GFC_FPE_INVALID | GFC_FPE_DENORMAL |
2865 GFC_FPE_ZERO | GFC_FPE_OVERFLOW | GFC_FPE_UNDERFLOW}.)
2866 @end multitable
2868 @item @emph{Example}:
2869 @smallexample
2870   /* Use gfortran 4.9 default options.  */
2871   static int options[] = @{68, 511, 0, 0, 1, 1, 0, 0, 31@};
2872   _gfortran_set_options (9, &options);
2873 @end smallexample
2874 @end table
2877 @node _gfortran_set_convert
2878 @subsection @code{_gfortran_set_convert} --- Set endian conversion
2879 @fnindex _gfortran_set_convert
2880 @cindex libgfortran initialization, set_convert
2882 @table @asis
2883 @item @emph{Description}:
2884 @code{_gfortran_set_convert} set the representation of data for
2885 unformatted files.
2887 @item @emph{Syntax}:
2888 @code{void _gfortran_set_convert (int conv)}
2890 @item @emph{Arguments}:
2891 @multitable @columnfractions .15 .70
2892 @item @var{conv} @tab Endian conversion, possible values:
2893 GFC_CONVERT_NATIVE (0, default), GFC_CONVERT_SWAP (1),
2894 GFC_CONVERT_BIG (2), GFC_CONVERT_LITTLE (3).
2895 @end multitable
2897 @item @emph{Example}:
2898 @smallexample
2899 int main (int argc, char *argv[])
2901   /* Initialize libgfortran.  */
2902   _gfortran_set_args (argc, argv);
2903   _gfortran_set_convert (1);
2904   return 0;
2906 @end smallexample
2907 @end table
2910 @node _gfortran_set_record_marker
2911 @subsection @code{_gfortran_set_record_marker} --- Set length of record markers
2912 @fnindex _gfortran_set_record_marker
2913 @cindex libgfortran initialization, set_record_marker
2915 @table @asis
2916 @item @emph{Description}:
2917 @code{_gfortran_set_record_marker} sets the length of record markers
2918 for unformatted files.
2920 @item @emph{Syntax}:
2921 @code{void _gfortran_set_record_marker (int val)}
2923 @item @emph{Arguments}:
2924 @multitable @columnfractions .15 .70
2925 @item @var{val} @tab Length of the record marker; valid values
2926 are 4 and 8.  Default is 4.
2927 @end multitable
2929 @item @emph{Example}:
2930 @smallexample
2931 int main (int argc, char *argv[])
2933   /* Initialize libgfortran.  */
2934   _gfortran_set_args (argc, argv);
2935   _gfortran_set_record_marker (8);
2936   return 0;
2938 @end smallexample
2939 @end table
2942 @node _gfortran_set_fpe
2943 @subsection @code{_gfortran_set_fpe} --- Enable floating point exception traps
2944 @fnindex _gfortran_set_fpe
2945 @cindex libgfortran initialization, set_fpe
2947 @table @asis
2948 @item @emph{Description}:
2949 @code{_gfortran_set_fpe} enables floating point exception traps for
2950 the specified exceptions.  On most systems, this will result in a
2951 SIGFPE signal being sent and the program being aborted.
2953 @item @emph{Syntax}:
2954 @code{void _gfortran_set_fpe (int val)}
2956 @item @emph{Arguments}:
2957 @multitable @columnfractions .15 .70
2958 @item @var{option}[0] @tab IEEE exceptions.  Possible values are
2959 (bitwise or-ed) zero (0, default) no trapping,
2960 @code{GFC_FPE_INVALID} (1), @code{GFC_FPE_DENORMAL} (2),
2961 @code{GFC_FPE_ZERO} (4), @code{GFC_FPE_OVERFLOW} (8),
2962 @code{GFC_FPE_UNDERFLOW} (16), and @code{GFC_FPE_INEXACT} (32).
2963 @end multitable
2965 @item @emph{Example}:
2966 @smallexample
2967 int main (int argc, char *argv[])
2969   /* Initialize libgfortran.  */
2970   _gfortran_set_args (argc, argv);
2971   /* FPE for invalid operations such as SQRT(-1.0).  */
2972   _gfortran_set_fpe (1);
2973   return 0;
2975 @end smallexample
2976 @end table
2979 @node _gfortran_set_max_subrecord_length
2980 @subsection @code{_gfortran_set_max_subrecord_length} --- Set subrecord length
2981 @fnindex _gfortran_set_max_subrecord_length
2982 @cindex libgfortran initialization, set_max_subrecord_length
2984 @table @asis
2985 @item @emph{Description}:
2986 @code{_gfortran_set_max_subrecord_length} set the maximum length
2987 for a subrecord.  This option only makes sense for testing and
2988 debugging of unformatted I/O.
2990 @item @emph{Syntax}:
2991 @code{void _gfortran_set_max_subrecord_length (int val)}
2993 @item @emph{Arguments}:
2994 @multitable @columnfractions .15 .70
2995 @item @var{val} @tab the maximum length for a subrecord;
2996 the maximum permitted value is 2147483639, which is also
2997 the default.
2998 @end multitable
3000 @item @emph{Example}:
3001 @smallexample
3002 int main (int argc, char *argv[])
3004   /* Initialize libgfortran.  */
3005   _gfortran_set_args (argc, argv);
3006   _gfortran_set_max_subrecord_length (8);
3007   return 0;
3009 @end smallexample
3010 @end table
3013 @node Naming and argument-passing conventions
3014 @section Naming and argument-passing conventions
3016 This section gives an overview about the naming convention of procedures
3017 and global variables and about the argument passing conventions used by
3018 GNU Fortran.  If a C binding has been specified, the naming convention
3019 and some of the argument-passing conventions change.  If possible,
3020 mixed-language and mixed-compiler projects should use the better defined
3021 C binding for interoperability.  See @pxref{Interoperability with C}.
3023 @menu
3024 * Naming conventions::
3025 * Argument passing conventions::
3026 @end menu
3029 @node Naming conventions
3030 @subsection Naming conventions
3032 According the Fortran standard, valid Fortran names consist of a letter
3033 between @code{A} to @code{Z}, @code{a} to @code{z}, digits @code{0},
3034 @code{1} to @code{9} and underscores (@code{_}) with the restriction
3035 that names may only start with a letter.  As vendor extension, the
3036 dollar sign (@code{$}) is additionally permitted with the option
3037 @option{-fdollar-ok}, but not as first character and only if the
3038 target system supports it.
3040 By default, the procedure name is the lower-cased Fortran name with an
3041 appended underscore (@code{_}); using @option{-fno-underscoring} no
3042 underscore is appended while @code{-fsecond-underscore} appends two
3043 underscores.  Depending on the target system and the calling convention,
3044 the procedure might be additionally dressed; for instance, on 32bit
3045 Windows with @code{stdcall}, an at-sign @code{@@} followed by an integer
3046 number is appended.  For the changing the calling convention, see
3047 @pxref{GNU Fortran Compiler Directives}.
3049 For common blocks, the same convention is used, i.e. by default an
3050 underscore is appended to the lower-cased Fortran name.  Blank commons
3051 have the name @code{__BLNK__}.
3053 For procedures and variables declared in the specification space of a
3054 module, the name is formed by @code{__}, followed by the lower-cased
3055 module name, @code{_MOD_}, and the lower-cased Fortran name.  Note that
3056 no underscore is appended.
3059 @node Argument passing conventions
3060 @subsection Argument passing conventions
3062 Subroutines do not return a value (matching C99's @code{void}) while
3063 functions either return a value as specified in the platform ABI or
3064 the result variable is passed as hidden argument to the function and
3065 no result is returned.  A hidden result variable is used when the
3066 result variable is an array or of type @code{CHARACTER}.
3068 Arguments are passed according to the platform ABI. In particular,
3069 complex arguments might not be compatible to a struct with two real
3070 components for the real and imaginary part. The argument passing
3071 matches the one of C99's @code{_Complex}.  Functions with scalar
3072 complex result variables return their value and do not use a
3073 by-reference argument.  Note that with the @option{-ff2c} option,
3074 the argument passing is modified and no longer completely matches
3075 the platform ABI.  Some other Fortran compilers use @code{f2c}
3076 semantic by default; this might cause problems with
3077 interoperablility. 
3079 GNU Fortran passes most arguments by reference, i.e. by passing a
3080 pointer to the data.  Note that the compiler might use a temporary
3081 variable into which the actual argument has been copied, if required
3082 semantically (copy-in/copy-out).
3084 For arguments with @code{ALLOCATABLE} and @code{POINTER}
3085 attribute (including procedure pointers), a pointer to the pointer
3086 is passed such that the pointer address can be modified in the
3087 procedure.
3089 For dummy arguments with the @code{VALUE} attribute: Scalar arguments
3090 of the type @code{INTEGER}, @code{LOGICAL}, @code{REAL} and
3091 @code{COMPLEX} are passed by value according to the platform ABI.
3092 (As vendor extension and not recommended, using @code{%VAL()} in the
3093 call to a procedure has the same effect.) For @code{TYPE(C_PTR)} and
3094 procedure pointers, the pointer itself is passed such that it can be
3095 modified without affecting the caller.
3096 @c FIXME: Document how VALUE is handled for CHARACTER, TYPE,
3097 @c CLASS and arrays, i.e. whether the copy-in is done in the caller
3098 @c or in the callee.
3100 For Boolean (@code{LOGICAL}) arguments, please note that GCC expects
3101 only the integer value 0 and 1.  If a GNU Fortran @code{LOGICAL}
3102 variable contains another integer value, the result is undefined.
3103 As some other Fortran compilers use @math{-1} for @code{.TRUE.},
3104 extra care has to be taken -- such as passing the value as
3105 @code{INTEGER}.  (The same value restriction also applies to other
3106 front ends of GCC, e.g. to GCC's C99 compiler for @code{_Bool}
3107 or GCC's Ada compiler for @code{Boolean}.)
3109 For arguments of @code{CHARACTER} type, the character length is passed
3110 as hidden argument.  For deferred-length strings, the value is passed
3111 by reference, otherwise by value.  The character length has the type
3112 @code{INTEGER(kind=4)}.  Note with C binding, @code{CHARACTER(len=1)}
3113 result variables are returned according to the platform ABI and no
3114 hidden length argument is used for dummy arguments; with @code{VALUE},
3115 those variables are passed by value.
3117 For @code{OPTIONAL} dummy arguments, an absent argument is denoted
3118 by a NULL pointer, except for scalar dummy arguments of type
3119 @code{INTEGER}, @code{LOGICAL}, @code{REAL} and @code{COMPLEX}
3120 which have the @code{VALUE} attribute.  For those, a hidden Boolean
3121 argument (@code{logical(kind=C_bool),value}) is used to indicate
3122 whether the argument is present.
3124 Arguments which are assumed-shape, assumed-rank or deferred-rank
3125 arrays or, with @option{-fcoarray=lib}, allocatable scalar coarrays use
3126 an array descriptor.  All other arrays pass the address of the
3127 first element of the array.  With @option{-fcoarray=lib}, the token
3128 and the offset belonging to nonallocatable coarrays dummy arguments
3129 are passed as hidden argument along the character length hidden
3130 arguments.  The token is an oparque pointer identifying the coarray
3131 and the offset is a passed-by-value integer of kind @code{C_PTRDIFF_T},
3132 denoting the byte offset between the base address of the coarray and
3133 the passed scalar or first element of the passed array.
3135 The arguments are passed in the following order
3136 @itemize @bullet
3137 @item Result variable, when the function result is passed by reference
3138 @item Character length of the function result, if it is a of type
3139 @code{CHARACTER} and no C binding is used
3140 @item The arguments in the order in which they appear in the Fortran
3141 declaration
3142 @item The the present status for optional arguments with value attribute,
3143 which are internally passed by value
3144 @item The character length and/or coarray token and offset for the first
3145 argument which is a @code{CHARACTER} or a nonallocatable coarray dummy
3146 argument, followed by the hidden arguments of the next dummy argument
3147 of such a type
3148 @end itemize
3152 @c Intrinsic Procedures
3153 @c ---------------------------------------------------------------------
3155 @include intrinsic.texi
3158 @tex
3159 \blankpart
3160 @end tex
3162 @c ---------------------------------------------------------------------
3163 @c Contributing
3164 @c ---------------------------------------------------------------------
3166 @node Contributing
3167 @unnumbered Contributing
3168 @cindex Contributing
3170 Free software is only possible if people contribute to efforts
3171 to create it.
3172 We're always in need of more people helping out with ideas
3173 and comments, writing documentation and contributing code.
3175 If you want to contribute to GNU Fortran,
3176 have a look at the long lists of projects you can take on.
3177 Some of these projects are small,
3178 some of them are large;
3179 some are completely orthogonal to the rest of what is
3180 happening on GNU Fortran,
3181 but others are ``mainstream'' projects in need of enthusiastic hackers.
3182 All of these projects are important!
3183 We will eventually get around to the things here,
3184 but they are also things doable by someone who is willing and able.
3186 @menu
3187 * Contributors::
3188 * Projects::
3189 * Proposed Extensions::
3190 @end menu
3193 @node Contributors
3194 @section Contributors to GNU Fortran
3195 @cindex Contributors
3196 @cindex Credits
3197 @cindex Authors
3199 Most of the parser was hand-crafted by @emph{Andy Vaught}, who is
3200 also the initiator of the whole project.  Thanks Andy!
3201 Most of the interface with GCC was written by @emph{Paul Brook}.
3203 The following individuals have contributed code and/or
3204 ideas and significant help to the GNU Fortran project
3205 (in alphabetical order):
3207 @itemize @minus
3208 @item Janne Blomqvist
3209 @item Steven Bosscher
3210 @item Paul Brook
3211 @item Tobias Burnus
3212 @item Fran@,{c}ois-Xavier Coudert
3213 @item Bud Davis
3214 @item Jerry DeLisle
3215 @item Erik Edelmann
3216 @item Bernhard Fischer
3217 @item Daniel Franke
3218 @item Richard Guenther
3219 @item Richard Henderson
3220 @item Katherine Holcomb
3221 @item Jakub Jelinek
3222 @item Niels Kristian Bech Jensen
3223 @item Steven Johnson
3224 @item Steven G. Kargl
3225 @item Thomas Koenig
3226 @item Asher Langton
3227 @item H. J. Lu
3228 @item Toon Moene
3229 @item Brooks Moses
3230 @item Andrew Pinski
3231 @item Tim Prince
3232 @item Christopher D. Rickett
3233 @item Richard Sandiford
3234 @item Tobias Schl@"uter
3235 @item Roger Sayle
3236 @item Paul Thomas
3237 @item Andy Vaught
3238 @item Feng Wang
3239 @item Janus Weil
3240 @item Daniel Kraft
3241 @end itemize
3243 The following people have contributed bug reports,
3244 smaller or larger patches,
3245 and much needed feedback and encouragement for the
3246 GNU Fortran project: 
3248 @itemize @minus
3249 @item Bill Clodius
3250 @item Dominique d'Humi@`eres
3251 @item Kate Hedstrom
3252 @item Erik Schnetter
3253 @item Joost VandeVondele
3254 @end itemize
3256 Many other individuals have helped debug,
3257 test and improve the GNU Fortran compiler over the past few years,
3258 and we welcome you to do the same!
3259 If you already have done so,
3260 and you would like to see your name listed in the
3261 list above, please contact us.
3264 @node Projects
3265 @section Projects
3267 @table @emph
3269 @item Help build the test suite
3270 Solicit more code for donation to the test suite: the more extensive the
3271 testsuite, the smaller the risk of breaking things in the future! We can
3272 keep code private on request.
3274 @item Bug hunting/squishing
3275 Find bugs and write more test cases! Test cases are especially very
3276 welcome, because it allows us to concentrate on fixing bugs instead of
3277 isolating them.  Going through the bugzilla database at
3278 @url{http://gcc.gnu.org/@/bugzilla/} to reduce testcases posted there and
3279 add more information (for example, for which version does the testcase
3280 work, for which versions does it fail?) is also very helpful.
3282 @end table
3285 @node Proposed Extensions
3286 @section Proposed Extensions
3288 Here's a list of proposed extensions for the GNU Fortran compiler, in no particular
3289 order.  Most of these are necessary to be fully compatible with
3290 existing Fortran compilers, but they are not part of the official
3291 J3 Fortran 95 standard.
3293 @subsection Compiler extensions: 
3294 @itemize @bullet
3295 @item
3296 User-specified alignment rules for structures.
3298 @item
3299 Automatically extend single precision constants to double.
3301 @item
3302 Compile code that conserves memory by dynamically allocating common and
3303 module storage either on stack or heap.
3305 @item
3306 Compile flag to generate code for array conformance checking (suggest -CC).
3308 @item
3309 User control of symbol names (underscores, etc).
3311 @item
3312 Compile setting for maximum size of stack frame size before spilling
3313 parts to static or heap.
3315 @item
3316 Flag to force local variables into static space.
3318 @item
3319 Flag to force local variables onto stack.
3320 @end itemize
3323 @subsection Environment Options
3324 @itemize @bullet
3325 @item
3326 Pluggable library modules for random numbers, linear algebra.
3327 LA should use BLAS calling conventions.
3329 @item
3330 Environment variables controlling actions on arithmetic exceptions like
3331 overflow, underflow, precision loss---Generate NaN, abort, default.
3332 action.
3334 @item
3335 Set precision for fp units that support it (i387).
3337 @item
3338 Variable for setting fp rounding mode.
3340 @item
3341 Variable to fill uninitialized variables with a user-defined bit
3342 pattern.
3344 @item
3345 Environment variable controlling filename that is opened for that unit
3346 number.
3348 @item
3349 Environment variable to clear/trash memory being freed.
3351 @item
3352 Environment variable to control tracing of allocations and frees.
3354 @item
3355 Environment variable to display allocated memory at normal program end.
3357 @item
3358 Environment variable for filename for * IO-unit.
3360 @item
3361 Environment variable for temporary file directory.
3363 @item
3364 Environment variable forcing standard output to be line buffered (Unix).
3366 @end itemize
3369 @c ---------------------------------------------------------------------
3370 @c GNU General Public License
3371 @c ---------------------------------------------------------------------
3373 @include gpl_v3.texi
3377 @c ---------------------------------------------------------------------
3378 @c GNU Free Documentation License
3379 @c ---------------------------------------------------------------------
3381 @include fdl.texi
3385 @c ---------------------------------------------------------------------
3386 @c Funding Free Software
3387 @c ---------------------------------------------------------------------
3389 @include funding.texi
3391 @c ---------------------------------------------------------------------
3392 @c Indices
3393 @c ---------------------------------------------------------------------
3395 @node Option Index
3396 @unnumbered Option Index
3397 @command{gfortran}'s command line options are indexed here without any
3398 initial @samp{-} or @samp{--}.  Where an option has both positive and
3399 negative forms (such as -foption and -fno-option), relevant entries in
3400 the manual are indexed under the most appropriate form; it may sometimes
3401 be useful to look up both forms.
3402 @printindex op
3404 @node Keyword Index
3405 @unnumbered Keyword Index
3406 @printindex cp
3408 @bye