Fix handling of temporary files.
[official-gcc.git] / gcc / fortran / gfortran.texi
blob96662c49423fb7205ee801a486138c67772ed941
1 \input texinfo  @c -*-texinfo-*-
2 @c %**start of header
3 @setfilename gfortran.info
4 @set copyrights-gfortran 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012
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 * Mixed-Language Programming::    Interoperability with C
186 * Extensions::           Language extensions implemented by GNU Fortran.
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 In the future, the GNU Fortran compiler will also support ISO/IEC
526 1539-1:2004 (Fortran 2003), ISO/IEC 1539-1:2010 (Fortran 2008) and
527 future Fortran standards.  Partial support of the Fortran 2003 and
528 Fortran 2008 standard is already provided; the current status of the
529 support is reported in the @ref{Fortran 2003 status} and
530 @ref{Fortran 2008 status} sections of the documentation.
532 Additionally, the GNU Fortran compilers supports the OpenMP specification
533 (version 3.1, @url{http://openmp.org/@/wp/@/openmp-specifications/}).
535 @node Varying Length Character Strings
536 @subsection Varying Length Character Strings
537 @cindex Varying length character strings
538 @cindex Varying length strings
539 @cindex strings, varying length
541 The Fortran 95 standard specifies in Part 2 (ISO/IEC 1539-2:2000)
542 varying length character strings.  While GNU Fortran currently does not
543 support such strings directly, there exist two Fortran implementations
544 for them, which work with GNU Fortran.  They can be found at
545 @uref{http://www.fortran.com/@/iso_varying_string.f95} and at
546 @uref{ftp://ftp.nag.co.uk/@/sc22wg5/@/ISO_VARYING_STRING/}.
550 @c =====================================================================
551 @c PART I: INVOCATION REFERENCE
552 @c =====================================================================
554 @tex
555 \part{I}{Invoking GNU Fortran}
556 @end tex
558 @c ---------------------------------------------------------------------
559 @c Compiler Options
560 @c ---------------------------------------------------------------------
562 @include invoke.texi
565 @c ---------------------------------------------------------------------
566 @c Runtime
567 @c ---------------------------------------------------------------------
569 @node Runtime
570 @chapter Runtime:  Influencing runtime behavior with environment variables
571 @cindex environment variable
573 The behavior of the @command{gfortran} can be influenced by
574 environment variables.
576 Malformed environment variables are silently ignored.
578 @menu
579 * TMPDIR:: Directory for scratch files
580 * GFORTRAN_STDIN_UNIT:: Unit number for standard input
581 * GFORTRAN_STDOUT_UNIT:: Unit number for standard output
582 * GFORTRAN_STDERR_UNIT:: Unit number for standard error
583 * GFORTRAN_UNBUFFERED_ALL:: Do not buffer I/O for all units.
584 * GFORTRAN_UNBUFFERED_PRECONNECTED:: Do not buffer I/O for preconnected units.
585 * GFORTRAN_SHOW_LOCUS::  Show location for runtime errors
586 * GFORTRAN_OPTIONAL_PLUS:: Print leading + where permitted
587 * GFORTRAN_DEFAULT_RECL:: Default record length for new files
588 * GFORTRAN_LIST_SEPARATOR::  Separator for list output
589 * GFORTRAN_CONVERT_UNIT::  Set endianness for unformatted I/O
590 * GFORTRAN_ERROR_BACKTRACE:: Show backtrace on run-time errors
591 @end menu
593 @node TMPDIR
594 @section @env{TMPDIR}---Directory for scratch files
596 When opening a file with @code{STATUS='SCRATCH'}, GNU Fortran tries to
597 create the file in one of the potential directories by testing each
598 directory in the order below.
600 @enumerate
601 @item
602 The environment variable @env{TMPDIR}, if it exists.
604 @item
605 On the MinGW target, the directory returned by the @code{GetTempPath}
606 function. Alternatively, on the Cygwin target, the @env{TMP} and
607 @env{TEMP} environment variables, if they exist, in that order.
609 @item
610 The @code{P_tmpdir} macro if it is defined, otherwise the directory
611 @file{/tmp}.
612 @end enumerate
614 @node GFORTRAN_STDIN_UNIT
615 @section @env{GFORTRAN_STDIN_UNIT}---Unit number for standard input
617 This environment variable can be used to select the unit number
618 preconnected to standard input.  This must be a positive integer.
619 The default value is 5.
621 @node GFORTRAN_STDOUT_UNIT
622 @section @env{GFORTRAN_STDOUT_UNIT}---Unit number for standard output
624 This environment variable can be used to select the unit number
625 preconnected to standard output.  This must be a positive integer.
626 The default value is 6.
628 @node GFORTRAN_STDERR_UNIT
629 @section @env{GFORTRAN_STDERR_UNIT}---Unit number for standard error
631 This environment variable can be used to select the unit number
632 preconnected to standard error.  This must be a positive integer.
633 The default value is 0.
635 @node GFORTRAN_UNBUFFERED_ALL
636 @section @env{GFORTRAN_UNBUFFERED_ALL}---Do not buffer I/O on all units
638 This environment variable controls whether all I/O is unbuffered.  If
639 the first letter is @samp{y}, @samp{Y} or @samp{1}, all I/O is
640 unbuffered.  This will slow down small sequential reads and writes.  If
641 the first letter is @samp{n}, @samp{N} or @samp{0}, I/O is buffered.
642 This is the default.
644 @node GFORTRAN_UNBUFFERED_PRECONNECTED
645 @section @env{GFORTRAN_UNBUFFERED_PRECONNECTED}---Do not buffer I/O on preconnected units
647 The environment variable named @env{GFORTRAN_UNBUFFERED_PRECONNECTED} controls
648 whether I/O on a preconnected unit (i.e.@: STDOUT or STDERR) is unbuffered.  If 
649 the first letter is @samp{y}, @samp{Y} or @samp{1}, I/O is unbuffered.  This
650 will slow down small sequential reads and writes.  If the first letter
651 is @samp{n}, @samp{N} or @samp{0}, I/O is buffered.  This is the default.
653 @node GFORTRAN_SHOW_LOCUS
654 @section @env{GFORTRAN_SHOW_LOCUS}---Show location for runtime errors
656 If the first letter is @samp{y}, @samp{Y} or @samp{1}, filename and
657 line numbers for runtime errors are printed.  If the first letter is
658 @samp{n}, @samp{N} or @samp{0}, do not print filename and line numbers
659 for runtime errors.  The default is to print the location.
661 @node GFORTRAN_OPTIONAL_PLUS
662 @section @env{GFORTRAN_OPTIONAL_PLUS}---Print leading + where permitted
664 If the first letter is @samp{y}, @samp{Y} or @samp{1},
665 a plus sign is printed
666 where permitted by the Fortran standard.  If the first letter
667 is @samp{n}, @samp{N} or @samp{0}, a plus sign is not printed
668 in most cases.  Default is not to print plus signs.
670 @node GFORTRAN_DEFAULT_RECL
671 @section @env{GFORTRAN_DEFAULT_RECL}---Default record length for new files
673 This environment variable specifies the default record length, in
674 bytes, for files which are opened without a @code{RECL} tag in the
675 @code{OPEN} statement.  This must be a positive integer.  The
676 default value is 1073741824 bytes (1 GB).
678 @node GFORTRAN_LIST_SEPARATOR
679 @section @env{GFORTRAN_LIST_SEPARATOR}---Separator for list output
681 This environment variable specifies the separator when writing
682 list-directed output.  It may contain any number of spaces and
683 at most one comma.  If you specify this on the command line,
684 be sure to quote spaces, as in
685 @smallexample
686 $ GFORTRAN_LIST_SEPARATOR='  ,  ' ./a.out
687 @end smallexample
688 when @command{a.out} is the compiled Fortran program that you want to run.
689 Default is a single space.
691 @node GFORTRAN_CONVERT_UNIT
692 @section @env{GFORTRAN_CONVERT_UNIT}---Set endianness for unformatted I/O
694 By setting the @env{GFORTRAN_CONVERT_UNIT} variable, it is possible
695 to change the representation of data for unformatted files.
696 The syntax for the @env{GFORTRAN_CONVERT_UNIT} variable is:
697 @smallexample
698 GFORTRAN_CONVERT_UNIT: mode | mode ';' exception | exception ;
699 mode: 'native' | 'swap' | 'big_endian' | 'little_endian' ;
700 exception: mode ':' unit_list | unit_list ;
701 unit_list: unit_spec | unit_list unit_spec ;
702 unit_spec: INTEGER | INTEGER '-' INTEGER ;
703 @end smallexample
704 The variable consists of an optional default mode, followed by
705 a list of optional exceptions, which are separated by semicolons
706 from the preceding default and each other.  Each exception consists
707 of a format and a comma-separated list of units.  Valid values for
708 the modes are the same as for the @code{CONVERT} specifier:
710 @itemize @w{}
711 @item @code{NATIVE} Use the native format.  This is the default.
712 @item @code{SWAP} Swap between little- and big-endian.
713 @item @code{LITTLE_ENDIAN} Use the little-endian format
714 for unformatted files.
715 @item @code{BIG_ENDIAN} Use the big-endian format for unformatted files.
716 @end itemize
717 A missing mode for an exception is taken to mean @code{BIG_ENDIAN}.
718 Examples of values for @env{GFORTRAN_CONVERT_UNIT} are:
719 @itemize @w{}
720 @item @code{'big_endian'}  Do all unformatted I/O in big_endian mode.
721 @item @code{'little_endian;native:10-20,25'}  Do all unformatted I/O 
722 in little_endian mode, except for units 10 to 20 and 25, which are in
723 native format.
724 @item @code{'10-20'}  Units 10 to 20 are big-endian, the rest is native.
725 @end itemize
727 Setting the environment variables should be done on the command
728 line or via the @command{export}
729 command for @command{sh}-compatible shells and via @command{setenv}
730 for @command{csh}-compatible shells.
732 Example for @command{sh}:
733 @smallexample
734 $ gfortran foo.f90
735 $ GFORTRAN_CONVERT_UNIT='big_endian;native:10-20' ./a.out
736 @end smallexample
738 Example code for @command{csh}:
739 @smallexample
740 % gfortran foo.f90
741 % setenv GFORTRAN_CONVERT_UNIT 'big_endian;native:10-20'
742 % ./a.out
743 @end smallexample
745 Using anything but the native representation for unformatted data
746 carries a significant speed overhead.  If speed in this area matters
747 to you, it is best if you use this only for data that needs to be
748 portable.
750 @xref{CONVERT specifier}, for an alternative way to specify the
751 data representation for unformatted files.  @xref{Runtime Options}, for
752 setting a default data representation for the whole program.  The
753 @code{CONVERT} specifier overrides the @option{-fconvert} compile options.
755 @emph{Note that the values specified via the GFORTRAN_CONVERT_UNIT
756 environment variable will override the CONVERT specifier in the
757 open statement}.  This is to give control over data formats to
758 users who do not have the source code of their program available.
760 @node GFORTRAN_ERROR_BACKTRACE
761 @section @env{GFORTRAN_ERROR_BACKTRACE}---Show backtrace on run-time errors
763 If the @env{GFORTRAN_ERROR_BACKTRACE} variable is set to @samp{y},
764 @samp{Y} or @samp{1} (only the first letter is relevant) then a
765 backtrace is printed when a serious run-time error occurs.  To disable
766 the backtracing, set the variable to @samp{n}, @samp{N}, @samp{0}.
767 Default is to print a backtrace unless the @option{-fno-backtrace}
768 compile option was used.
770 @c =====================================================================
771 @c PART II: LANGUAGE REFERENCE
772 @c =====================================================================
774 @tex
775 \part{II}{Language Reference}
776 @end tex
778 @c ---------------------------------------------------------------------
779 @c Fortran 2003 and 2008 Status
780 @c ---------------------------------------------------------------------
782 @node Fortran 2003 and 2008 status
783 @chapter Fortran 2003 and 2008 Status
785 @menu
786 * Fortran 2003 status::
787 * Fortran 2008 status::
788 * TS 29113 status::
789 @end menu
791 @node Fortran 2003 status
792 @section Fortran 2003 status
794 GNU Fortran supports several Fortran 2003 features; an incomplete
795 list can be found below.  See also the
796 @uref{http://gcc.gnu.org/wiki/Fortran2003, wiki page} about Fortran 2003.
798 @itemize
799 @item Procedure pointers including procedure-pointer components with
800 @code{PASS} attribute.
802 @item Procedures which are bound to a derived type (type-bound procedures)
803 including @code{PASS}, @code{PROCEDURE} and @code{GENERIC}, and
804 operators bound to a type.
806 @item Abstract interfaces and type extension with the possibility to
807 override type-bound procedures or to have deferred binding.
809 @item Polymorphic entities (``@code{CLASS}'') for derived types -- including
810 @code{SAME_TYPE_AS}, @code{EXTENDS_TYPE_OF} and @code{SELECT TYPE}.
811 Note that unlimited polymorphism is currently not supported.
813 @item Generic interface names, which have the same name as derived types,
814 are now supported. This allows one to write constructor functions.  Note
815 that Fortran does not support static constructor functions.  For static
816 variables, only default initialization or structure-constructor
817 initialization are available.
819 @item The @code{ASSOCIATE} construct.
821 @item Interoperability with C including enumerations, 
823 @item In structure constructors the components with default values may be
824 omitted.
826 @item Extensions to the @code{ALLOCATE} statement, allowing for a
827 type-specification with type parameter and for allocation and initialization
828 from a @code{SOURCE=} expression; @code{ALLOCATE} and @code{DEALLOCATE}
829 optionally return an error message string via @code{ERRMSG=}.
831 @item Reallocation on assignment: If an intrinsic assignment is
832 used, an allocatable variable on the left-hand side is automatically allocated
833 (if unallocated) or reallocated (if the shape is different). Currently, scalar
834 deferred character length left-hand sides are correctly handled but arrays
835 are not yet fully implemented.
837 @item Transferring of allocations via @code{MOVE_ALLOC}.
839 @item The @code{PRIVATE} and @code{PUBLIC} attributes may be given individually
840 to derived-type components.
842 @item In pointer assignments, the lower bound may be specified and
843 the remapping of elements is supported.
845 @item For pointers an @code{INTENT} may be specified which affect the
846 association status not the value of the pointer target.
848 @item Intrinsics @code{command_argument_count}, @code{get_command},
849 @code{get_command_argument}, and @code{get_environment_variable}.
851 @item Support for Unicode characters (ISO 10646) and UTF-8, including
852 the @code{SELECTED_CHAR_KIND} and @code{NEW_LINE} intrinsic functions.
854 @item Support for binary, octal and hexadecimal (BOZ) constants in the
855 intrinsic functions @code{INT}, @code{REAL}, @code{CMPLX} and @code{DBLE}.
857 @item Support for namelist variables with allocatable and pointer
858 attribute and nonconstant length type parameter.
860 @item
861 @cindex array, constructors
862 @cindex @code{[...]}
863 Array constructors using square brackets.  That is, @code{[...]} rather
864 than @code{(/.../)}.  Type-specification for array constructors like
865 @code{(/ some-type :: ... /)}.
867 @item Extensions to the specification and initialization expressions,
868 including the support for intrinsics with real and complex arguments.
870 @item Support for the asynchronous input/output syntax; however, the
871 data transfer is currently always synchronously performed. 
873 @item
874 @cindex @code{FLUSH} statement
875 @cindex statement, @code{FLUSH}
876 @code{FLUSH} statement.
878 @item
879 @cindex @code{IOMSG=} specifier
880 @code{IOMSG=} specifier for I/O statements.
882 @item
883 @cindex @code{ENUM} statement
884 @cindex @code{ENUMERATOR} statement
885 @cindex statement, @code{ENUM}
886 @cindex statement, @code{ENUMERATOR}
887 @opindex @code{fshort-enums}
888 Support for the declaration of enumeration constants via the
889 @code{ENUM} and @code{ENUMERATOR} statements.  Interoperability with
890 @command{gcc} is guaranteed also for the case where the
891 @command{-fshort-enums} command line option is given.
893 @item
894 @cindex TR 15581
895 TR 15581:
896 @itemize
897 @item
898 @cindex @code{ALLOCATABLE} dummy arguments
899 @code{ALLOCATABLE} dummy arguments.
900 @item
901 @cindex @code{ALLOCATABLE} function results
902 @code{ALLOCATABLE} function results
903 @item
904 @cindex @code{ALLOCATABLE} components of derived types
905 @code{ALLOCATABLE} components of derived types
906 @end itemize
908 @item
909 @cindex @code{STREAM} I/O
910 @cindex @code{ACCESS='STREAM'} I/O
911 The @code{OPEN} statement supports the @code{ACCESS='STREAM'} specifier,
912 allowing I/O without any record structure.
914 @item
915 Namelist input/output for internal files.
917 @item Further I/O extensions: Rounding during formatted output, using of
918 a decimal comma instead of a decimal point, setting whether a plus sign
919 should appear for positive numbers.
921 @item
922 @cindex @code{PROTECTED} statement
923 @cindex statement, @code{PROTECTED}
924 The @code{PROTECTED} statement and attribute.
926 @item
927 @cindex @code{VALUE} statement
928 @cindex statement, @code{VALUE}
929 The @code{VALUE} statement and attribute.
931 @item
932 @cindex @code{VOLATILE} statement
933 @cindex statement, @code{VOLATILE}
934 The @code{VOLATILE} statement and attribute.
936 @item
937 @cindex @code{IMPORT} statement
938 @cindex statement, @code{IMPORT}
939 The @code{IMPORT} statement, allowing to import
940 host-associated derived types.
942 @item The intrinsic modules @code{ISO_FORTRAN_ENVIRONMENT} is supported,
943 which contains parameters of the I/O units, storage sizes. Additionally,
944 procedures for C interoperability are available in the @code{ISO_C_BINDING}
945 module.
947 @item
948 @cindex @code{USE, INTRINSIC} statement
949 @cindex statement, @code{USE, INTRINSIC}
950 @cindex @code{ISO_FORTRAN_ENV} statement
951 @cindex statement, @code{ISO_FORTRAN_ENV}
952 @code{USE} statement with @code{INTRINSIC} and @code{NON_INTRINSIC}
953 attribute; supported intrinsic modules: @code{ISO_FORTRAN_ENV},
954 @code{ISO_C_BINDING}, @code{OMP_LIB} and @code{OMP_LIB_KINDS}.
956 @item
957 Renaming of operators in the @code{USE} statement.
959 @end itemize
962 @node Fortran 2008 status
963 @section Fortran 2008 status
965 The latest version of the Fortran standard is ISO/IEC 1539-1:2010, informally
966 known as Fortran 2008.  The official version is available from International
967 Organization for Standardization (ISO) or its national member organizations.
968 The the final draft (FDIS) can be downloaded free of charge from
969 @url{http://www.nag.co.uk/@/sc22wg5/@/links.html}.  Fortran is developed by the
970 Working Group 5 of Sub-Committee 22 of the Joint Technical Committee 1 of the
971 International Organization for Standardization and the International
972 Electrotechnical Commission (IEC).  This group is known as
973 @uref{http://www.nag.co.uk/sc22wg5/, WG5}.
975 The GNU Fortran compiler supports several of the new features of Fortran 2008;
976 the @uref{http://gcc.gnu.org/wiki/Fortran2008Status, wiki} has some information
977 about the current Fortran 2008 implementation status.  In particular, the
978 following is implemented.
980 @itemize
981 @item The @option{-std=f2008} option and support for the file extensions 
982 @file{.f08} and @file{.F08}.
984 @item The @code{OPEN} statement now supports the @code{NEWUNIT=} option,
985 which returns a unique file unit, thus preventing inadvertent use of the
986 same unit in different parts of the program.
988 @item The @code{g0} format descriptor and unlimited format items.
990 @item The mathematical intrinsics @code{ASINH}, @code{ACOSH}, @code{ATANH},
991 @code{ERF}, @code{ERFC}, @code{GAMMA}, @code{LOG_GAMMA}, @code{BESSEL_J0},
992 @code{BESSEL_J1}, @code{BESSEL_JN}, @code{BESSEL_Y0}, @code{BESSEL_Y1},
993 @code{BESSEL_YN}, @code{HYPOT}, @code{NORM2}, and @code{ERFC_SCALED}.
995 @item Using complex arguments with @code{TAN}, @code{SINH}, @code{COSH},
996 @code{TANH}, @code{ASIN}, @code{ACOS}, and @code{ATAN} is now possible;
997 @code{ATAN}(@var{Y},@var{X}) is now an alias for @code{ATAN2}(@var{Y},@var{X}).
999 @item Support of the @code{PARITY} intrinsic functions.
1001 @item The following bit intrinsics: @code{LEADZ} and @code{TRAILZ} for
1002 counting the number of leading and trailing zero bits, @code{POPCNT} and
1003 @code{POPPAR} for counting the number of one bits and returning the parity;
1004 @code{BGE}, @code{BGT}, @code{BLE}, and @code{BLT} for bitwise comparisons;
1005 @code{DSHIFTL} and @code{DSHIFTR} for combined left and right shifts,
1006 @code{MASKL} and @code{MASKR} for simple left and right justified masks,
1007 @code{MERGE_BITS} for a bitwise merge using a mask, @code{SHIFTA},
1008 @code{SHIFTL} and @code{SHIFTR} for shift operations, and the
1009 transformational bit intrinsics @code{IALL}, @code{IANY} and @code{IPARITY}.
1011 @item Support of the @code{EXECUTE_COMMAND_LINE} intrinsic subroutine.
1013 @item Support for the @code{STORAGE_SIZE} intrinsic inquiry function.
1015 @item The @code{INT@{8,16,32@}} and @code{REAL@{32,64,128@}} kind type
1016 parameters and the array-valued named constants @code{INTEGER_KINDS},
1017 @code{LOGICAL_KINDS}, @code{REAL_KINDS} and @code{CHARACTER_KINDS} of
1018 the intrinsic module @code{ISO_FORTRAN_ENV}.
1020 @item The module procedures @code{C_SIZEOF} of the intrinsic module
1021 @code{ISO_C_BINDINGS} and @code{COMPILER_VERSION} and @code{COMPILER_OPTIONS}
1022 of @code{ISO_FORTRAN_ENV}.
1024 @item Coarray support for serial programs with @option{-fcoarray=single} flag
1025 and experimental support for multiple images with the @option{-fcoarray=lib}
1026 flag.
1028 @item The @code{DO CONCURRENT} construct is supported.
1030 @item The @code{BLOCK} construct is supported.
1032 @item The @code{STOP} and the new @code{ERROR STOP} statements now
1033 support all constant expressions.
1035 @item Support for the @code{CONTIGUOUS} attribute.
1037 @item Support for @code{ALLOCATE} with @code{MOLD}.
1039 @item Support for the @code{IMPURE} attribute for procedures, which
1040 allows for @code{ELEMENTAL} procedures without the restrictions of
1041 @code{PURE}.
1043 @item Null pointers (including @code{NULL()}) and not-allocated variables
1044 can be used as actual argument to optional non-pointer, non-allocatable
1045 dummy arguments, denoting an absent argument.
1047 @item Non-pointer variables with @code{TARGET} attribute can be used as
1048 actual argument to @code{POINTER} dummies with @code{INTENT(IN)}.
1050 @item Pointers including procedure pointers and those in a derived
1051 type (pointer components) can now be initialized by a target instead
1052 of only by @code{NULL}.
1054 @item The @code{EXIT} statement (with construct-name) can be now be
1055 used to leave not only the @code{DO} but also the @code{ASSOCIATE},
1056 @code{BLOCK}, @code{IF}, @code{SELECT CASE} and @code{SELECT TYPE}
1057 constructs.
1059 @item Internal procedures can now be used as actual argument.
1061 @item Minor features: obsolesce diagnostics for @code{ENTRY} with
1062 @option{-std=f2008}; a line may start with a semicolon; for internal
1063 and module procedures @code{END} can be used instead of
1064 @code{END SUBROUTINE} and @code{END FUNCTION}; @code{SELECTED_REAL_KIND}
1065 now also takes a @code{RADIX} argument; intrinsic types are supported
1066 for @code{TYPE}(@var{intrinsic-type-spec}); multiple type-bound procedures
1067 can be declared in a single @code{PROCEDURE} statement; implied-shape
1068 arrays are supported for named constants (@code{PARAMETER}).
1069 @end itemize
1073 @node TS 29113 status
1074 @section Technical Specification 29113 Status
1076 GNU Fortran supports some of the new features of the Technical
1077 Specification (TS) 29113 on Further Interoperability of Fortran with C.
1078 The @uref{http://gcc.gnu.org/wiki/TS29113Status, wiki} has some information
1079 about the current TS 29113 implementation status.  In particular, the
1080 following is implemented.
1082 @itemize
1083 @item The @option{-std=f2008ts} option.
1085 @item The @code{OPTIONAL} attribute is allowed for dummy arguments
1086 of @code{BIND(C) procedures.}
1088 @item The RANK intrinsic is supported.
1090 @item GNU Fortran's implementation for variables with @code{ASYNCHRONOUS}
1091 attribute is compatible with TS 29113.
1092 @end itemize
1096 @c ---------------------------------------------------------------------
1097 @c Compiler Characteristics
1098 @c ---------------------------------------------------------------------
1100 @node Compiler Characteristics
1101 @chapter Compiler Characteristics
1103 This chapter describes certain characteristics of the GNU Fortran
1104 compiler, that are not specified by the Fortran standard, but which
1105 might in some way or another become visible to the programmer.
1107 @menu
1108 * KIND Type Parameters::
1109 * Internal representation of LOGICAL variables::
1110 * Thread-safety of the runtime library::
1111 * Data consistency and durability::
1112 @end menu
1115 @node KIND Type Parameters
1116 @section KIND Type Parameters
1117 @cindex kind
1119 The @code{KIND} type parameters supported by GNU Fortran for the primitive
1120 data types are:
1122 @table @code
1124 @item INTEGER
1125 1, 2, 4, 8*, 16*, default: 4 (1)
1127 @item LOGICAL
1128 1, 2, 4, 8*, 16*, default: 4 (1)
1130 @item REAL
1131 4, 8, 10*, 16*, default: 4 (2)
1133 @item COMPLEX
1134 4, 8, 10*, 16*, default: 4 (2)
1136 @item CHARACTER
1137 1, 4, default: 1
1139 @end table
1141 @noindent
1142 * = not available on all systems @*
1143 (1) Unless -fdefault-integer-8 is used @*
1144 (2) Unless -fdefault-real-8 is used
1146 @noindent
1147 The @code{KIND} value matches the storage size in bytes, except for
1148 @code{COMPLEX} where the storage size is twice as much (or both real and
1149 imaginary part are a real value of the given size).  It is recommended to use
1150 the @code{SELECTED_CHAR_KIND}, @code{SELECTED_INT_KIND} and
1151 @code{SELECTED_REAL_KIND} intrinsics or the @code{INT8}, @code{INT16},
1152 @code{INT32}, @code{INT64}, @code{REAL32}, @code{REAL64}, and @code{REAL128}
1153 parameters of the @code{ISO_FORTRAN_ENV} module instead of the concrete values.
1154 The available kind parameters can be found in the constant arrays
1155 @code{CHARACTER_KINDS}, @code{INTEGER_KINDS}, @code{LOGICAL_KINDS} and
1156 @code{REAL_KINDS} in the @code{ISO_FORTRAN_ENV} module
1157 (see @ref{ISO_FORTRAN_ENV}).
1160 @node Internal representation of LOGICAL variables
1161 @section Internal representation of LOGICAL variables
1162 @cindex logical, variable representation
1164 The Fortran standard does not specify how variables of @code{LOGICAL}
1165 type are represented, beyond requiring that @code{LOGICAL} variables
1166 of default kind have the same storage size as default @code{INTEGER}
1167 and @code{REAL} variables.  The GNU Fortran internal representation is
1168 as follows.
1170 A @code{LOGICAL(KIND=N)} variable is represented as an
1171 @code{INTEGER(KIND=N)} variable, however, with only two permissible
1172 values: @code{1} for @code{.TRUE.} and @code{0} for
1173 @code{.FALSE.}.  Any other integer value results in undefined behavior.
1175 Note that for mixed-language programming using the
1176 @code{ISO_C_BINDING} feature, there is a @code{C_BOOL} kind that can
1177 be used to create @code{LOGICAL(KIND=C_BOOL)} variables which are
1178 interoperable with the C99 _Bool type.  The C99 _Bool type has an
1179 internal representation described in the C99 standard, which is
1180 identical to the above description, i.e. with 1 for true and 0 for
1181 false being the only permissible values.  Thus the internal
1182 representation of @code{LOGICAL} variables in GNU Fortran is identical
1183 to C99 _Bool, except for a possible difference in storage size
1184 depending on the kind.
1187 @node Thread-safety of the runtime library
1188 @section Thread-safety of the runtime library
1189 @cindex thread-safety, threads
1191 GNU Fortran can be used in programs with multiple threads, e.g.@: by
1192 using OpenMP, by calling OS thread handling functions via the
1193 @code{ISO_C_BINDING} facility, or by GNU Fortran compiled library code
1194 being called from a multi-threaded program.
1196 The GNU Fortran runtime library, (@code{libgfortran}), supports being
1197 called concurrently from multiple threads with the following
1198 exceptions. 
1200 During library initialization, the C @code{getenv} function is used,
1201 which need not be thread-safe.  Similarly, the @code{getenv}
1202 function is used to implement the @code{GET_ENVIRONMENT_VARIABLE} and
1203 @code{GETENV} intrinsics.  It is the responsibility of the user to
1204 ensure that the environment is not being updated concurrently when any
1205 of these actions are taking place.
1207 The @code{EXECUTE_COMMAND_LINE} and @code{SYSTEM} intrinsics are
1208 implemented with the @code{system} function, which need not be
1209 thread-safe.  It is the responsibility of the user to ensure that
1210 @code{system} is not called concurrently.
1212 Finally, for platforms not supporting thread-safe POSIX functions,
1213 further functionality might not be thread-safe.  For details, please
1214 consult the documentation for your operating system.
1217 @node Data consistency and durability
1218 @section Data consistency and durability
1219 @cindex consistency, durability
1221 This section contains a brief overview of data and metadata
1222 consistency and durability issues when doing I/O.
1224 With respect to durability, GNU Fortran makes no effort to ensure that
1225 data is committed to stable storage. If this is required, the GNU
1226 Fortran programmer can use the intrinsic @code{FNUM} to retrieve the
1227 low level file descriptor corresponding to an open Fortran unit. Then,
1228 using e.g. the @code{ISO_C_BINDING} feature, one can call the
1229 underlying system call to flush dirty data to stable storage, such as
1230 @code{fsync} on POSIX, @code{_commit} on MingW, or @code{fcntl(fd,
1231 F_FULLSYNC, 0)} on Mac OS X. The following example shows how to call
1232 fsync:
1234 @smallexample
1235   ! Declare the interface for POSIX fsync function
1236   interface
1237     function fsync (fd) bind(c,name="fsync")
1238     use iso_c_binding, only: c_int
1239       integer(c_int), value :: fd
1240       integer(c_int) :: fsync
1241     end function fsync
1242   end interface
1244   ! Variable declaration
1245   integer :: ret
1247   ! Opening unit 10
1248   open (10,file="foo")
1250   ! ...
1251   ! Perform I/O on unit 10
1252   ! ...
1254   ! Flush and sync
1255   flush(10)
1256   ret = fsync(fnum(10))
1258   ! Handle possible error
1259   if (ret /= 0) stop "Error calling FSYNC"
1260 @end smallexample
1262 With respect to consistency, for regular files GNU Fortran uses
1263 buffered I/O in order to improve performance. This buffer is flushed
1264 automatically when full and in some other situations, e.g. when
1265 closing a unit. It can also be explicitly flushed with the
1266 @code{FLUSH} statement. Also, the buffering can be turned off with the
1267 @code{GFORTRAN_UNBUFFERED_ALL} and
1268 @code{GFORTRAN_UNBUFFERED_PRECONNECTED} environment variables. Special
1269 files, such as terminals and pipes, are always unbuffered. Sometimes,
1270 however, further things may need to be done in order to allow other
1271 processes to see data that GNU Fortran has written, as follows.
1273 The Windows platform supports a relaxed metadata consistency model,
1274 where file metadata is written to the directory lazily. This means
1275 that, for instance, the @code{dir} command can show a stale size for a
1276 file. One can force a directory metadata update by closing the unit,
1277 or by calling @code{_commit} on the file descriptor. Note, though,
1278 that @code{_commit} will force all dirty data to stable storage, which
1279 is often a very slow operation.
1281 The Network File System (NFS) implements a relaxed consistency model
1282 called open-to-close consistency. Closing a file forces dirty data and
1283 metadata to be flushed to the server, and opening a file forces the
1284 client to contact the server in order to revalidate cached
1285 data. @code{fsync} will also force a flush of dirty data and metadata
1286 to the server. Similar to @code{open} and @code{close}, acquiring and
1287 releasing @code{fcntl} file locks, if the server supports them, will
1288 also force cache validation and flushing dirty data and metadata.
1291 @c ---------------------------------------------------------------------
1292 @c Extensions
1293 @c ---------------------------------------------------------------------
1295 @c Maybe this chapter should be merged with the 'Standards' section,
1296 @c whenever that is written :-)
1298 @node Extensions
1299 @chapter Extensions
1300 @cindex extensions
1302 The two sections below detail the extensions to standard Fortran that are
1303 implemented in GNU Fortran, as well as some of the popular or
1304 historically important extensions that are not (or not yet) implemented.
1305 For the latter case, we explain the alternatives available to GNU Fortran
1306 users, including replacement by standard-conforming code or GNU
1307 extensions.
1309 @menu
1310 * Extensions implemented in GNU Fortran::
1311 * Extensions not implemented in GNU Fortran::
1312 @end menu
1315 @node Extensions implemented in GNU Fortran
1316 @section Extensions implemented in GNU Fortran
1317 @cindex extensions, implemented
1319 GNU Fortran implements a number of extensions over standard
1320 Fortran.  This chapter contains information on their syntax and
1321 meaning.  There are currently two categories of GNU Fortran
1322 extensions, those that provide functionality beyond that provided
1323 by any standard, and those that are supported by GNU Fortran
1324 purely for backward compatibility with legacy compilers.  By default,
1325 @option{-std=gnu} allows the compiler to accept both types of
1326 extensions, but to warn about the use of the latter.  Specifying
1327 either @option{-std=f95}, @option{-std=f2003} or @option{-std=f2008}
1328 disables both types of extensions, and @option{-std=legacy} allows both
1329 without warning.
1331 @menu
1332 * Old-style kind specifications::
1333 * Old-style variable initialization::
1334 * Extensions to namelist::
1335 * X format descriptor without count field::
1336 * Commas in FORMAT specifications::
1337 * Missing period in FORMAT specifications::
1338 * I/O item lists::
1339 * BOZ literal constants::
1340 * @code{Q} exponent-letter::
1341 * Real array indices::
1342 * Unary operators::
1343 * Implicitly convert LOGICAL and INTEGER values::
1344 * Hollerith constants support::
1345 * Cray pointers::
1346 * CONVERT specifier::
1347 * OpenMP::
1348 * Argument list functions::
1349 @end menu
1351 @node Old-style kind specifications
1352 @subsection Old-style kind specifications
1353 @cindex kind, old-style
1355 GNU Fortran allows old-style kind specifications in declarations.  These
1356 look like:
1357 @smallexample
1358       TYPESPEC*size x,y,z
1359 @end smallexample
1360 @noindent
1361 where @code{TYPESPEC} is a basic type (@code{INTEGER}, @code{REAL},
1362 etc.), and where @code{size} is a byte count corresponding to the
1363 storage size of a valid kind for that type.  (For @code{COMPLEX}
1364 variables, @code{size} is the total size of the real and imaginary
1365 parts.)  The statement then declares @code{x}, @code{y} and @code{z} to
1366 be of type @code{TYPESPEC} with the appropriate kind.  This is
1367 equivalent to the standard-conforming declaration
1368 @smallexample
1369       TYPESPEC(k) x,y,z
1370 @end smallexample
1371 @noindent
1372 where @code{k} is the kind parameter suitable for the intended precision.  As
1373 kind parameters are implementation-dependent, use the @code{KIND},
1374 @code{SELECTED_INT_KIND} and @code{SELECTED_REAL_KIND} intrinsics to retrieve
1375 the correct value, for instance @code{REAL*8 x} can be replaced by:
1376 @smallexample
1377 INTEGER, PARAMETER :: dbl = KIND(1.0d0)
1378 REAL(KIND=dbl) :: x
1379 @end smallexample
1381 @node Old-style variable initialization
1382 @subsection Old-style variable initialization
1384 GNU Fortran allows old-style initialization of variables of the
1385 form:
1386 @smallexample
1387       INTEGER i/1/,j/2/
1388       REAL x(2,2) /3*0.,1./
1389 @end smallexample
1390 The syntax for the initializers is as for the @code{DATA} statement, but
1391 unlike in a @code{DATA} statement, an initializer only applies to the
1392 variable immediately preceding the initialization.  In other words,
1393 something like @code{INTEGER I,J/2,3/} is not valid.  This style of
1394 initialization is only allowed in declarations without double colons
1395 (@code{::}); the double colons were introduced in Fortran 90, which also
1396 introduced a standard syntax for initializing variables in type
1397 declarations.
1399 Examples of standard-conforming code equivalent to the above example
1400 are:
1401 @smallexample
1402 ! Fortran 90
1403       INTEGER :: i = 1, j = 2
1404       REAL :: x(2,2) = RESHAPE((/0.,0.,0.,1./),SHAPE(x))
1405 ! Fortran 77
1406       INTEGER i, j
1407       REAL x(2,2)
1408       DATA i/1/, j/2/, x/3*0.,1./
1409 @end smallexample
1411 Note that variables which are explicitly initialized in declarations
1412 or in @code{DATA} statements automatically acquire the @code{SAVE}
1413 attribute.
1415 @node Extensions to namelist
1416 @subsection Extensions to namelist
1417 @cindex Namelist
1419 GNU Fortran fully supports the Fortran 95 standard for namelist I/O
1420 including array qualifiers, substrings and fully qualified derived types.
1421 The output from a namelist write is compatible with namelist read.  The
1422 output has all names in upper case and indentation to column 1 after the
1423 namelist name.  Two extensions are permitted:
1425 Old-style use of @samp{$} instead of @samp{&}
1426 @smallexample
1427 $MYNML
1428  X(:)%Y(2) = 1.0 2.0 3.0
1429  CH(1:4) = "abcd"
1430 $END
1431 @end smallexample
1433 It should be noted that the default terminator is @samp{/} rather than
1434 @samp{&END}.
1436 Querying of the namelist when inputting from stdin.  After at least
1437 one space, entering @samp{?} sends to stdout the namelist name and the names of
1438 the variables in the namelist:
1439 @smallexample
1442 &mynml
1444  x%y
1445  ch
1446 &end
1447 @end smallexample
1449 Entering @samp{=?} outputs the namelist to stdout, as if
1450 @code{WRITE(*,NML = mynml)} had been called:
1451 @smallexample
1454 &MYNML
1455  X(1)%Y=  0.000000    ,  1.000000    ,  0.000000    ,
1456  X(2)%Y=  0.000000    ,  2.000000    ,  0.000000    ,
1457  X(3)%Y=  0.000000    ,  3.000000    ,  0.000000    ,
1458  CH=abcd,  /
1459 @end smallexample
1461 To aid this dialog, when input is from stdin, errors send their
1462 messages to stderr and execution continues, even if @code{IOSTAT} is set.
1464 @code{PRINT} namelist is permitted.  This causes an error if
1465 @option{-std=f95} is used.
1466 @smallexample
1467 PROGRAM test_print
1468   REAL, dimension (4)  ::  x = (/1.0, 2.0, 3.0, 4.0/)
1469   NAMELIST /mynml/ x
1470   PRINT mynml
1471 END PROGRAM test_print
1472 @end smallexample
1474 Expanded namelist reads are permitted.  This causes an error if 
1475 @option{-std=f95} is used.  In the following example, the first element
1476 of the array will be given the value 0.00 and the two succeeding
1477 elements will be given the values 1.00 and 2.00.
1478 @smallexample
1479 &MYNML
1480   X(1,1) = 0.00 , 1.00 , 2.00
1482 @end smallexample
1484 @node X format descriptor without count field
1485 @subsection @code{X} format descriptor without count field
1487 To support legacy codes, GNU Fortran permits the count field of the
1488 @code{X} edit descriptor in @code{FORMAT} statements to be omitted.
1489 When omitted, the count is implicitly assumed to be one.
1491 @smallexample
1492        PRINT 10, 2, 3
1493 10     FORMAT (I1, X, I1)
1494 @end smallexample
1496 @node Commas in FORMAT specifications
1497 @subsection Commas in @code{FORMAT} specifications
1499 To support legacy codes, GNU Fortran allows the comma separator
1500 to be omitted immediately before and after character string edit
1501 descriptors in @code{FORMAT} statements.
1503 @smallexample
1504        PRINT 10, 2, 3
1505 10     FORMAT ('FOO='I1' BAR='I2)
1506 @end smallexample
1509 @node Missing period in FORMAT specifications
1510 @subsection Missing period in @code{FORMAT} specifications
1512 To support legacy codes, GNU Fortran allows missing periods in format
1513 specifications if and only if @option{-std=legacy} is given on the
1514 command line.  This is considered non-conforming code and is
1515 discouraged.
1517 @smallexample
1518        REAL :: value
1519        READ(*,10) value
1520 10     FORMAT ('F4')
1521 @end smallexample
1523 @node I/O item lists
1524 @subsection I/O item lists
1525 @cindex I/O item lists
1527 To support legacy codes, GNU Fortran allows the input item list
1528 of the @code{READ} statement, and the output item lists of the
1529 @code{WRITE} and @code{PRINT} statements, to start with a comma.
1531 @node @code{Q} exponent-letter
1532 @subsection @code{Q} exponent-letter
1533 @cindex @code{Q} exponent-letter
1535 GNU Fortran accepts real literal constants with an exponent-letter
1536 of @code{Q}, for example, @code{1.23Q45}.  The constant is interpreted
1537 as a @code{REAL(16)} entity on targets that support this type.  If
1538 the target does not support @code{REAL(16)} but has a @code{REAL(10)}
1539 type, then the real-literal-constant will be interpreted as a
1540 @code{REAL(10)} entity.  In the absence of @code{REAL(16)} and
1541 @code{REAL(10)}, an error will occur.
1543 @node BOZ literal constants
1544 @subsection BOZ literal constants
1545 @cindex BOZ literal constants
1547 Besides decimal constants, Fortran also supports binary (@code{b}),
1548 octal (@code{o}) and hexadecimal (@code{z}) integer constants.  The
1549 syntax is: @samp{prefix quote digits quote}, were the prefix is
1550 either @code{b}, @code{o} or @code{z}, quote is either @code{'} or
1551 @code{"} and the digits are for binary @code{0} or @code{1}, for
1552 octal between @code{0} and @code{7}, and for hexadecimal between
1553 @code{0} and @code{F}.  (Example: @code{b'01011101'}.)
1555 Up to Fortran 95, BOZ literals were only allowed to initialize
1556 integer variables in DATA statements.  Since Fortran 2003 BOZ literals
1557 are also allowed as argument of @code{REAL}, @code{DBLE}, @code{INT}
1558 and @code{CMPLX}; the result is the same as if the integer BOZ
1559 literal had been converted by @code{TRANSFER} to, respectively,
1560 @code{real}, @code{double precision}, @code{integer} or @code{complex}.
1561 As GNU Fortran extension the intrinsic procedures @code{FLOAT},
1562 @code{DFLOAT}, @code{COMPLEX} and @code{DCMPLX} are treated alike.
1564 As an extension, GNU Fortran allows hexadecimal BOZ literal constants to
1565 be specified using the @code{X} prefix, in addition to the standard
1566 @code{Z} prefix.  The BOZ literal can also be specified by adding a
1567 suffix to the string, for example, @code{Z'ABC'} and @code{'ABC'Z} are
1568 equivalent.
1570 Furthermore, GNU Fortran allows using BOZ literal constants outside
1571 DATA statements and the four intrinsic functions allowed by Fortran 2003.
1572 In DATA statements, in direct assignments, where the right-hand side
1573 only contains a BOZ literal constant, and for old-style initializers of
1574 the form @code{integer i /o'0173'/}, the constant is transferred
1575 as if @code{TRANSFER} had been used; for @code{COMPLEX} numbers, only
1576 the real part is initialized unless @code{CMPLX} is used.  In all other
1577 cases, the BOZ literal constant is converted to an @code{INTEGER} value with
1578 the largest decimal representation.  This value is then converted
1579 numerically to the type and kind of the variable in question.
1580 (For instance, @code{real :: r = b'0000001' + 1} initializes @code{r}
1581 with @code{2.0}.) As different compilers implement the extension
1582 differently, one should be careful when doing bitwise initialization
1583 of non-integer variables.
1585 Note that initializing an @code{INTEGER} variable with a statement such
1586 as @code{DATA i/Z'FFFFFFFF'/} will give an integer overflow error rather
1587 than the desired result of @math{-1} when @code{i} is a 32-bit integer
1588 on a system that supports 64-bit integers.  The @samp{-fno-range-check}
1589 option can be used as a workaround for legacy code that initializes
1590 integers in this manner.
1592 @node Real array indices
1593 @subsection Real array indices
1594 @cindex array, indices of type real
1596 As an extension, GNU Fortran allows the use of @code{REAL} expressions
1597 or variables as array indices.
1599 @node Unary operators
1600 @subsection Unary operators
1601 @cindex operators, unary
1603 As an extension, GNU Fortran allows unary plus and unary minus operators
1604 to appear as the second operand of binary arithmetic operators without
1605 the need for parenthesis.
1607 @smallexample
1608        X = Y * -Z
1609 @end smallexample
1611 @node Implicitly convert LOGICAL and INTEGER values
1612 @subsection Implicitly convert @code{LOGICAL} and @code{INTEGER} values
1613 @cindex conversion, to integer
1614 @cindex conversion, to logical
1616 As an extension for backwards compatibility with other compilers, GNU
1617 Fortran allows the implicit conversion of @code{LOGICAL} values to
1618 @code{INTEGER} values and vice versa.  When converting from a
1619 @code{LOGICAL} to an @code{INTEGER}, @code{.FALSE.} is interpreted as
1620 zero, and @code{.TRUE.} is interpreted as one.  When converting from
1621 @code{INTEGER} to @code{LOGICAL}, the value zero is interpreted as
1622 @code{.FALSE.} and any nonzero value is interpreted as @code{.TRUE.}.
1624 @smallexample
1625         LOGICAL :: l
1626         l = 1
1627 @end smallexample
1628 @smallexample
1629         INTEGER :: i
1630         i = .TRUE.
1631 @end smallexample
1633 However, there is no implicit conversion of @code{INTEGER} values in
1634 @code{if}-statements, nor of @code{LOGICAL} or @code{INTEGER} values
1635 in I/O operations.
1637 @node Hollerith constants support
1638 @subsection Hollerith constants support
1639 @cindex Hollerith constants
1641 GNU Fortran supports Hollerith constants in assignments, function
1642 arguments, and @code{DATA} and @code{ASSIGN} statements.  A Hollerith
1643 constant is written as a string of characters preceded by an integer
1644 constant indicating the character count, and the letter @code{H} or
1645 @code{h}, and stored in bytewise fashion in a numeric (@code{INTEGER},
1646 @code{REAL}, or @code{complex}) or @code{LOGICAL} variable.  The
1647 constant will be padded or truncated to fit the size of the variable in
1648 which it is stored.
1650 Examples of valid uses of Hollerith constants:
1651 @smallexample
1652       complex*16 x(2)
1653       data x /16Habcdefghijklmnop, 16Hqrstuvwxyz012345/
1654       x(1) = 16HABCDEFGHIJKLMNOP
1655       call foo (4h abc)
1656 @end smallexample
1658 Invalid Hollerith constants examples:
1659 @smallexample
1660       integer*4 a
1661       a = 8H12345678 ! Valid, but the Hollerith constant will be truncated.
1662       a = 0H         ! At least one character is needed.
1663 @end smallexample
1665 In general, Hollerith constants were used to provide a rudimentary
1666 facility for handling character strings in early Fortran compilers,
1667 prior to the introduction of @code{CHARACTER} variables in Fortran 77;
1668 in those cases, the standard-compliant equivalent is to convert the
1669 program to use proper character strings.  On occasion, there may be a
1670 case where the intent is specifically to initialize a numeric variable
1671 with a given byte sequence.  In these cases, the same result can be
1672 obtained by using the @code{TRANSFER} statement, as in this example.
1673 @smallexample
1674       INTEGER(KIND=4) :: a
1675       a = TRANSFER ("abcd", a)     ! equivalent to: a = 4Habcd
1676 @end smallexample
1679 @node Cray pointers
1680 @subsection Cray pointers
1681 @cindex pointer, Cray
1683 Cray pointers are part of a non-standard extension that provides a
1684 C-like pointer in Fortran.  This is accomplished through a pair of
1685 variables: an integer "pointer" that holds a memory address, and a
1686 "pointee" that is used to dereference the pointer.
1688 Pointer/pointee pairs are declared in statements of the form:
1689 @smallexample
1690         pointer ( <pointer> , <pointee> )
1691 @end smallexample
1693 @smallexample
1694         pointer ( <pointer1> , <pointee1> ), ( <pointer2> , <pointee2> ), ...
1695 @end smallexample
1696 The pointer is an integer that is intended to hold a memory address.
1697 The pointee may be an array or scalar.  A pointee can be an assumed
1698 size array---that is, the last dimension may be left unspecified by
1699 using a @code{*} in place of a value---but a pointee cannot be an
1700 assumed shape array.  No space is allocated for the pointee.
1702 The pointee may have its type declared before or after the pointer
1703 statement, and its array specification (if any) may be declared
1704 before, during, or after the pointer statement.  The pointer may be
1705 declared as an integer prior to the pointer statement.  However, some
1706 machines have default integer sizes that are different than the size
1707 of a pointer, and so the following code is not portable:
1708 @smallexample
1709         integer ipt
1710         pointer (ipt, iarr)
1711 @end smallexample
1712 If a pointer is declared with a kind that is too small, the compiler
1713 will issue a warning; the resulting binary will probably not work
1714 correctly, because the memory addresses stored in the pointers may be
1715 truncated.  It is safer to omit the first line of the above example;
1716 if explicit declaration of ipt's type is omitted, then the compiler
1717 will ensure that ipt is an integer variable large enough to hold a
1718 pointer.
1720 Pointer arithmetic is valid with Cray pointers, but it is not the same
1721 as C pointer arithmetic.  Cray pointers are just ordinary integers, so
1722 the user is responsible for determining how many bytes to add to a
1723 pointer in order to increment it.  Consider the following example:
1724 @smallexample
1725         real target(10)
1726         real pointee(10)
1727         pointer (ipt, pointee)
1728         ipt = loc (target)
1729         ipt = ipt + 1       
1730 @end smallexample
1731 The last statement does not set @code{ipt} to the address of
1732 @code{target(1)}, as it would in C pointer arithmetic.  Adding @code{1}
1733 to @code{ipt} just adds one byte to the address stored in @code{ipt}.
1735 Any expression involving the pointee will be translated to use the
1736 value stored in the pointer as the base address.
1738 To get the address of elements, this extension provides an intrinsic
1739 function @code{LOC()}.  The @code{LOC()} function is equivalent to the
1740 @code{&} operator in C, except the address is cast to an integer type:
1741 @smallexample
1742         real ar(10)
1743         pointer(ipt, arpte(10))
1744         real arpte
1745         ipt = loc(ar)  ! Makes arpte is an alias for ar
1746         arpte(1) = 1.0 ! Sets ar(1) to 1.0
1747 @end smallexample
1748 The pointer can also be set by a call to the @code{MALLOC} intrinsic
1749 (see @ref{MALLOC}).
1751 Cray pointees often are used to alias an existing variable.  For
1752 example:
1753 @smallexample
1754         integer target(10)
1755         integer iarr(10)
1756         pointer (ipt, iarr)
1757         ipt = loc(target)
1758 @end smallexample
1759 As long as @code{ipt} remains unchanged, @code{iarr} is now an alias for
1760 @code{target}.  The optimizer, however, will not detect this aliasing, so
1761 it is unsafe to use @code{iarr} and @code{target} simultaneously.  Using
1762 a pointee in any way that violates the Fortran aliasing rules or
1763 assumptions is illegal.  It is the user's responsibility to avoid doing
1764 this; the compiler works under the assumption that no such aliasing
1765 occurs.
1767 Cray pointers will work correctly when there is no aliasing (i.e., when
1768 they are used to access a dynamically allocated block of memory), and
1769 also in any routine where a pointee is used, but any variable with which
1770 it shares storage is not used.  Code that violates these rules may not
1771 run as the user intends.  This is not a bug in the optimizer; any code
1772 that violates the aliasing rules is illegal.  (Note that this is not
1773 unique to GNU Fortran; any Fortran compiler that supports Cray pointers
1774 will ``incorrectly'' optimize code with illegal aliasing.)
1776 There are a number of restrictions on the attributes that can be applied
1777 to Cray pointers and pointees.  Pointees may not have the
1778 @code{ALLOCATABLE}, @code{INTENT}, @code{OPTIONAL}, @code{DUMMY},
1779 @code{TARGET}, @code{INTRINSIC}, or @code{POINTER} attributes.  Pointers
1780 may not have the @code{DIMENSION}, @code{POINTER}, @code{TARGET},
1781 @code{ALLOCATABLE}, @code{EXTERNAL}, or @code{INTRINSIC} attributes, nor
1782 may they be function results.  Pointees may not occur in more than one
1783 pointer statement.  A pointee cannot be a pointer.  Pointees cannot occur
1784 in equivalence, common, or data statements.
1786 A Cray pointer may also point to a function or a subroutine.  For
1787 example, the following excerpt is valid:
1788 @smallexample
1789   implicit none
1790   external sub
1791   pointer (subptr,subpte)
1792   external subpte
1793   subptr = loc(sub)
1794   call subpte()
1795   [...]
1796   subroutine sub
1797   [...]
1798   end subroutine sub
1799 @end smallexample
1801 A pointer may be modified during the course of a program, and this
1802 will change the location to which the pointee refers.  However, when
1803 pointees are passed as arguments, they are treated as ordinary
1804 variables in the invoked function.  Subsequent changes to the pointer
1805 will not change the base address of the array that was passed.
1807 @node CONVERT specifier
1808 @subsection @code{CONVERT} specifier
1809 @cindex @code{CONVERT} specifier
1811 GNU Fortran allows the conversion of unformatted data between little-
1812 and big-endian representation to facilitate moving of data
1813 between different systems.  The conversion can be indicated with
1814 the @code{CONVERT} specifier on the @code{OPEN} statement.
1815 @xref{GFORTRAN_CONVERT_UNIT}, for an alternative way of specifying
1816 the data format via an environment variable.
1818 Valid values for @code{CONVERT} are:
1819 @itemize @w{}
1820 @item @code{CONVERT='NATIVE'} Use the native format.  This is the default.
1821 @item @code{CONVERT='SWAP'} Swap between little- and big-endian.
1822 @item @code{CONVERT='LITTLE_ENDIAN'} Use the little-endian representation
1823 for unformatted files.
1824 @item @code{CONVERT='BIG_ENDIAN'} Use the big-endian representation for
1825 unformatted files.
1826 @end itemize
1828 Using the option could look like this:
1829 @smallexample
1830   open(file='big.dat',form='unformatted',access='sequential', &
1831        convert='big_endian')
1832 @end smallexample
1834 The value of the conversion can be queried by using
1835 @code{INQUIRE(CONVERT=ch)}.  The values returned are
1836 @code{'BIG_ENDIAN'} and @code{'LITTLE_ENDIAN'}.
1838 @code{CONVERT} works between big- and little-endian for
1839 @code{INTEGER} values of all supported kinds and for @code{REAL}
1840 on IEEE systems of kinds 4 and 8.  Conversion between different
1841 ``extended double'' types on different architectures such as
1842 m68k and x86_64, which GNU Fortran
1843 supports as @code{REAL(KIND=10)} and @code{REAL(KIND=16)}, will
1844 probably not work.
1846 @emph{Note that the values specified via the GFORTRAN_CONVERT_UNIT
1847 environment variable will override the CONVERT specifier in the
1848 open statement}.  This is to give control over data formats to
1849 users who do not have the source code of their program available.
1851 Using anything but the native representation for unformatted data
1852 carries a significant speed overhead.  If speed in this area matters
1853 to you, it is best if you use this only for data that needs to be
1854 portable.
1856 @node OpenMP
1857 @subsection OpenMP
1858 @cindex OpenMP
1860 OpenMP (Open Multi-Processing) is an application programming
1861 interface (API) that supports multi-platform shared memory 
1862 multiprocessing programming in C/C++ and Fortran on many 
1863 architectures, including Unix and Microsoft Windows platforms.
1864 It consists of a set of compiler directives, library routines,
1865 and environment variables that influence run-time behavior.
1867 GNU Fortran strives to be compatible to the 
1868 @uref{http://www.openmp.org/mp-documents/spec31.pdf,
1869 OpenMP Application Program Interface v3.1}.
1871 To enable the processing of the OpenMP directive @code{!$omp} in
1872 free-form source code; the @code{c$omp}, @code{*$omp} and @code{!$omp}
1873 directives in fixed form; the @code{!$} conditional compilation sentinels
1874 in free form; and the @code{c$}, @code{*$} and @code{!$} sentinels
1875 in fixed form, @command{gfortran} needs to be invoked with the
1876 @option{-fopenmp}.  This also arranges for automatic linking of the
1877 GNU OpenMP runtime library @ref{Top,,libgomp,libgomp,GNU OpenMP
1878 runtime library}.
1880 The OpenMP Fortran runtime library routines are provided both in a
1881 form of a Fortran 90 module named @code{omp_lib} and in a form of
1882 a Fortran @code{include} file named @file{omp_lib.h}.
1884 An example of a parallelized loop taken from Appendix A.1 of
1885 the OpenMP Application Program Interface v2.5:
1886 @smallexample
1887 SUBROUTINE A1(N, A, B)
1888   INTEGER I, N
1889   REAL B(N), A(N)
1890 !$OMP PARALLEL DO !I is private by default
1891   DO I=2,N
1892     B(I) = (A(I) + A(I-1)) / 2.0
1893   ENDDO
1894 !$OMP END PARALLEL DO
1895 END SUBROUTINE A1
1896 @end smallexample
1898 Please note:
1899 @itemize
1900 @item
1901 @option{-fopenmp} implies @option{-frecursive}, i.e., all local arrays
1902 will be allocated on the stack.  When porting existing code to OpenMP,
1903 this may lead to surprising results, especially to segmentation faults
1904 if the stacksize is limited.
1906 @item
1907 On glibc-based systems, OpenMP enabled applications cannot be statically
1908 linked due to limitations of the underlying pthreads-implementation.  It
1909 might be possible to get a working solution if 
1910 @command{-Wl,--whole-archive -lpthread -Wl,--no-whole-archive} is added
1911 to the command line.  However, this is not supported by @command{gcc} and
1912 thus not recommended.
1913 @end itemize
1915 @node Argument list functions
1916 @subsection Argument list functions @code{%VAL}, @code{%REF} and @code{%LOC}
1917 @cindex argument list functions
1918 @cindex @code{%VAL}
1919 @cindex @code{%REF}
1920 @cindex @code{%LOC}
1922 GNU Fortran supports argument list functions @code{%VAL}, @code{%REF} 
1923 and @code{%LOC} statements, for backward compatibility with g77. 
1924 It is recommended that these should be used only for code that is 
1925 accessing facilities outside of GNU Fortran, such as operating system 
1926 or windowing facilities.  It is best to constrain such uses to isolated 
1927 portions of a program--portions that deal specifically and exclusively 
1928 with low-level, system-dependent facilities.  Such portions might well 
1929 provide a portable interface for use by the program as a whole, but are 
1930 themselves not portable, and should be thoroughly tested each time they 
1931 are rebuilt using a new compiler or version of a compiler.
1933 @code{%VAL} passes a scalar argument by value, @code{%REF} passes it by 
1934 reference and @code{%LOC} passes its memory location.  Since gfortran 
1935 already passes scalar arguments by reference, @code{%REF} is in effect 
1936 a do-nothing.  @code{%LOC} has the same effect as a Fortran pointer.
1938 An example of passing an argument by value to a C subroutine foo.:
1939 @smallexample
1941 C prototype      void foo_ (float x);
1943       external foo
1944       real*4 x
1945       x = 3.14159
1946       call foo (%VAL (x))
1947       end
1948 @end smallexample
1950 For details refer to the g77 manual
1951 @uref{http://gcc.gnu.org/@/onlinedocs/@/gcc-3.4.6/@/g77/@/index.html#Top}.
1953 Also, @code{c_by_val.f} and its partner @code{c_by_val.c} of the
1954 GNU Fortran testsuite are worth a look.
1957 @node Extensions not implemented in GNU Fortran
1958 @section Extensions not implemented in GNU Fortran
1959 @cindex extensions, not implemented
1961 The long history of the Fortran language, its wide use and broad
1962 userbase, the large number of different compiler vendors and the lack of
1963 some features crucial to users in the first standards have lead to the
1964 existence of a number of important extensions to the language.  While
1965 some of the most useful or popular extensions are supported by the GNU
1966 Fortran compiler, not all existing extensions are supported.  This section
1967 aims at listing these extensions and offering advice on how best make
1968 code that uses them running with the GNU Fortran compiler.
1970 @c More can be found here:
1971 @c   -- http://gcc.gnu.org/onlinedocs/gcc-3.4.6/g77/Missing-Features.html
1972 @c   -- the list of Fortran and libgfortran bugs closed as WONTFIX:
1973 @c      http://tinyurl.com/2u4h5y
1975 @menu
1976 * STRUCTURE and RECORD::
1977 @c * UNION and MAP::
1978 * ENCODE and DECODE statements::
1979 * Variable FORMAT expressions::
1980 @c * Q edit descriptor::
1981 @c * AUTOMATIC statement::
1982 @c * TYPE and ACCEPT I/O Statements::
1983 @c * .XOR. operator::
1984 @c * CARRIAGECONTROL, DEFAULTFILE, DISPOSE and RECORDTYPE I/O specifiers::
1985 @c * Omitted arguments in procedure call::
1986 * Alternate complex function syntax::
1987 @end menu
1990 @node STRUCTURE and RECORD
1991 @subsection @code{STRUCTURE} and @code{RECORD}
1992 @cindex @code{STRUCTURE}
1993 @cindex @code{RECORD}
1995 Structures are user-defined aggregate data types; this functionality was
1996 standardized in Fortran 90 with an different syntax, under the name of
1997 ``derived types''.  Here is an example of code using the non portable
1998 structure syntax:
2000 @example
2001 ! Declaring a structure named ``item'' and containing three fields:
2002 ! an integer ID, an description string and a floating-point price.
2003 STRUCTURE /item/
2004   INTEGER id
2005   CHARACTER(LEN=200) description
2006   REAL price
2007 END STRUCTURE
2009 ! Define two variables, an single record of type ``item''
2010 ! named ``pear'', and an array of items named ``store_catalog''
2011 RECORD /item/ pear, store_catalog(100)
2013 ! We can directly access the fields of both variables
2014 pear.id = 92316
2015 pear.description = "juicy D'Anjou pear"
2016 pear.price = 0.15
2017 store_catalog(7).id = 7831
2018 store_catalog(7).description = "milk bottle"
2019 store_catalog(7).price = 1.2
2021 ! We can also manipulate the whole structure
2022 store_catalog(12) = pear
2023 print *, store_catalog(12)
2024 @end example
2026 @noindent
2027 This code can easily be rewritten in the Fortran 90 syntax as following:
2029 @example
2030 ! ``STRUCTURE /name/ ... END STRUCTURE'' becomes
2031 ! ``TYPE name ... END TYPE''
2032 TYPE item
2033   INTEGER id
2034   CHARACTER(LEN=200) description
2035   REAL price
2036 END TYPE
2038 ! ``RECORD /name/ variable'' becomes ``TYPE(name) variable''
2039 TYPE(item) pear, store_catalog(100)
2041 ! Instead of using a dot (.) to access fields of a record, the
2042 ! standard syntax uses a percent sign (%)
2043 pear%id = 92316
2044 pear%description = "juicy D'Anjou pear"
2045 pear%price = 0.15
2046 store_catalog(7)%id = 7831
2047 store_catalog(7)%description = "milk bottle"
2048 store_catalog(7)%price = 1.2
2050 ! Assignments of a whole variable do not change
2051 store_catalog(12) = pear
2052 print *, store_catalog(12)
2053 @end example
2056 @c @node UNION and MAP
2057 @c @subsection @code{UNION} and @code{MAP}
2058 @c @cindex @code{UNION}
2059 @c @cindex @code{MAP}
2061 @c For help writing this one, see
2062 @c http://www.eng.umd.edu/~nsw/ench250/fortran1.htm#UNION and
2063 @c http://www.tacc.utexas.edu/services/userguides/pgi/pgiws_ug/pgi32u06.htm
2066 @node ENCODE and DECODE statements
2067 @subsection @code{ENCODE} and @code{DECODE} statements
2068 @cindex @code{ENCODE}
2069 @cindex @code{DECODE}
2071 GNU Fortran does not support the @code{ENCODE} and @code{DECODE}
2072 statements.  These statements are best replaced by @code{READ} and
2073 @code{WRITE} statements involving internal files (@code{CHARACTER}
2074 variables and arrays), which have been part of the Fortran standard since
2075 Fortran 77.  For example, replace a code fragment like
2077 @smallexample
2078       INTEGER*1 LINE(80)
2079       REAL A, B, C
2080 c     ... Code that sets LINE
2081       DECODE (80, 9000, LINE) A, B, C
2082  9000 FORMAT (1X, 3(F10.5))
2083 @end smallexample
2085 @noindent
2086 with the following:
2088 @smallexample
2089       CHARACTER(LEN=80) LINE
2090       REAL A, B, C
2091 c     ... Code that sets LINE
2092       READ (UNIT=LINE, FMT=9000) A, B, C
2093  9000 FORMAT (1X, 3(F10.5))
2094 @end smallexample
2096 Similarly, replace a code fragment like
2098 @smallexample
2099       INTEGER*1 LINE(80)
2100       REAL A, B, C
2101 c     ... Code that sets A, B and C
2102       ENCODE (80, 9000, LINE) A, B, C
2103  9000 FORMAT (1X, 'OUTPUT IS ', 3(F10.5))
2104 @end smallexample
2106 @noindent
2107 with the following:
2109 @smallexample
2110       CHARACTER(LEN=80) LINE
2111       REAL A, B, C
2112 c     ... Code that sets A, B and C
2113       WRITE (UNIT=LINE, FMT=9000) A, B, C
2114  9000 FORMAT (1X, 'OUTPUT IS ', 3(F10.5))
2115 @end smallexample
2118 @node Variable FORMAT expressions
2119 @subsection Variable @code{FORMAT} expressions
2120 @cindex @code{FORMAT}
2122 A variable @code{FORMAT} expression is format statement which includes
2123 angle brackets enclosing a Fortran expression: @code{FORMAT(I<N>)}.  GNU
2124 Fortran does not support this legacy extension.  The effect of variable
2125 format expressions can be reproduced by using the more powerful (and
2126 standard) combination of internal output and string formats.  For example,
2127 replace a code fragment like this:
2129 @smallexample
2130       WRITE(6,20) INT1
2131  20   FORMAT(I<N+1>)
2132 @end smallexample
2134 @noindent
2135 with the following:
2137 @smallexample
2138 c     Variable declaration
2139       CHARACTER(LEN=20) FMT
2140 c     
2141 c     Other code here...
2143       WRITE(FMT,'("(I", I0, ")")') N+1
2144       WRITE(6,FMT) INT1
2145 @end smallexample
2147 @noindent
2148 or with:
2150 @smallexample
2151 c     Variable declaration
2152       CHARACTER(LEN=20) FMT
2153 c     
2154 c     Other code here...
2156       WRITE(FMT,*) N+1
2157       WRITE(6,"(I" // ADJUSTL(FMT) // ")") INT1
2158 @end smallexample
2161 @node Alternate complex function syntax
2162 @subsection Alternate complex function syntax
2163 @cindex Complex function
2165 Some Fortran compilers, including @command{g77}, let the user declare
2166 complex functions with the syntax @code{COMPLEX FUNCTION name*16()}, as
2167 well as @code{COMPLEX*16 FUNCTION name()}.  Both are non-standard, legacy
2168 extensions.  @command{gfortran} accepts the latter form, which is more
2169 common, but not the former.
2173 @c ---------------------------------------------------------------------
2174 @c Mixed-Language Programming
2175 @c ---------------------------------------------------------------------
2177 @node Mixed-Language Programming
2178 @chapter Mixed-Language Programming
2179 @cindex Interoperability
2180 @cindex Mixed-language programming
2182 @menu
2183 * Interoperability with C::
2184 * GNU Fortran Compiler Directives::
2185 * Non-Fortran Main Program::
2186 @end menu
2188 This chapter is about mixed-language interoperability, but also applies
2189 if one links Fortran code compiled by different compilers.  In most cases,
2190 use of the C Binding features of the Fortran 2003 standard is sufficient,
2191 and their use is highly recommended.
2194 @node Interoperability with C
2195 @section Interoperability with C
2197 @menu
2198 * Intrinsic Types::
2199 * Derived Types and struct::
2200 * Interoperable Global Variables::
2201 * Interoperable Subroutines and Functions::
2202 * Working with Pointers::
2203 * Further Interoperability of Fortran with C::
2204 @end menu
2206 Since Fortran 2003 (ISO/IEC 1539-1:2004(E)) there is a
2207 standardized way to generate procedure and derived-type
2208 declarations and global variables which are interoperable with C
2209 (ISO/IEC 9899:1999).  The @code{bind(C)} attribute has been added
2210 to inform the compiler that a symbol shall be interoperable with C;
2211 also, some constraints are added.  Note, however, that not
2212 all C features have a Fortran equivalent or vice versa.  For instance,
2213 neither C's unsigned integers nor C's functions with variable number
2214 of arguments have an equivalent in Fortran.
2216 Note that array dimensions are reversely ordered in C and that arrays in
2217 C always start with index 0 while in Fortran they start by default with
2218 1.  Thus, an array declaration @code{A(n,m)} in Fortran matches
2219 @code{A[m][n]} in C and accessing the element @code{A(i,j)} matches
2220 @code{A[j-1][i-1]}.  The element following @code{A(i,j)} (C: @code{A[j-1][i-1]};
2221 assuming @math{i < n}) in memory is @code{A(i+1,j)} (C: @code{A[j-1][i]}).
2223 @node Intrinsic Types
2224 @subsection Intrinsic Types
2226 In order to ensure that exactly the same variable type and kind is used
2227 in C and Fortran, the named constants shall be used which are defined in the
2228 @code{ISO_C_BINDING} intrinsic module.  That module contains named constants
2229 for kind parameters and character named constants for the escape sequences
2230 in C.  For a list of the constants, see @ref{ISO_C_BINDING}.
2232 @node Derived Types and struct
2233 @subsection Derived Types and struct
2235 For compatibility of derived types with @code{struct}, one needs to use
2236 the @code{BIND(C)} attribute in the type declaration.  For instance, the
2237 following type declaration
2239 @smallexample
2240  USE ISO_C_BINDING
2241  TYPE, BIND(C) :: myType
2242    INTEGER(C_INT) :: i1, i2
2243    INTEGER(C_SIGNED_CHAR) :: i3
2244    REAL(C_DOUBLE) :: d1
2245    COMPLEX(C_FLOAT_COMPLEX) :: c1
2246    CHARACTER(KIND=C_CHAR) :: str(5)
2247  END TYPE
2248 @end smallexample
2250 matches the following @code{struct} declaration in C
2252 @smallexample
2253  struct @{
2254    int i1, i2;
2255    /* Note: "char" might be signed or unsigned.  */
2256    signed char i3;
2257    double d1;
2258    float _Complex c1;
2259    char str[5];
2260  @} myType;
2261 @end smallexample
2263 Derived types with the C binding attribute shall not have the @code{sequence}
2264 attribute, type parameters, the @code{extends} attribute, nor type-bound
2265 procedures.  Every component must be of interoperable type and kind and may not
2266 have the @code{pointer} or @code{allocatable} attribute.  The names of the
2267 variables are irrelevant for interoperability.
2269 As there exist no direct Fortran equivalents, neither unions nor structs
2270 with bit field or variable-length array members are interoperable.
2272 @node Interoperable Global Variables
2273 @subsection Interoperable Global Variables
2275 Variables can be made accessible from C using the C binding attribute,
2276 optionally together with specifying a binding name.  Those variables
2277 have to be declared in the declaration part of a @code{MODULE},
2278 be of interoperable type, and have neither the @code{pointer} nor
2279 the @code{allocatable} attribute.
2281 @smallexample
2282   MODULE m
2283     USE myType_module
2284     USE ISO_C_BINDING
2285     integer(C_INT), bind(C, name="_MyProject_flags") :: global_flag
2286     type(myType), bind(C) :: tp
2287   END MODULE
2288 @end smallexample
2290 Here, @code{_MyProject_flags} is the case-sensitive name of the variable
2291 as seen from C programs while @code{global_flag} is the case-insensitive
2292 name as seen from Fortran.  If no binding name is specified, as for
2293 @var{tp}, the C binding name is the (lowercase) Fortran binding name.
2294 If a binding name is specified, only a single variable may be after the
2295 double colon.  Note of warning: You cannot use a global variable to
2296 access @var{errno} of the C library as the C standard allows it to be
2297 a macro.  Use the @code{IERRNO} intrinsic (GNU extension) instead.
2299 @node Interoperable Subroutines and Functions
2300 @subsection Interoperable Subroutines and Functions
2302 Subroutines and functions have to have the @code{BIND(C)} attribute to
2303 be compatible with C.  The dummy argument declaration is relatively
2304 straightforward.  However, one needs to be careful because C uses
2305 call-by-value by default while Fortran behaves usually similar to
2306 call-by-reference.  Furthermore, strings and pointers are handled
2307 differently.  Note that only explicit size and assumed-size arrays are
2308 supported but not assumed-shape or allocatable arrays.
2310 To pass a variable by value, use the @code{VALUE} attribute.
2311 Thus the following C prototype
2313 @smallexample
2314 @code{int func(int i, int *j)}
2315 @end smallexample
2317 matches the Fortran declaration
2319 @smallexample
2320   integer(c_int) function func(i,j)
2321     use iso_c_binding, only: c_int
2322     integer(c_int), VALUE :: i
2323     integer(c_int) :: j
2324 @end smallexample
2326 Note that pointer arguments also frequently need the @code{VALUE} attribute,
2327 see @ref{Working with Pointers}.
2329 Strings are handled quite differently in C and Fortran.  In C a string
2330 is a @code{NUL}-terminated array of characters while in Fortran each string
2331 has a length associated with it and is thus not terminated (by e.g.
2332 @code{NUL}).  For example, if one wants to use the following C function,
2334 @smallexample
2335   #include <stdio.h>
2336   void print_C(char *string) /* equivalent: char string[]  */
2337   @{
2338      printf("%s\n", string);
2339   @}
2340 @end smallexample
2342 to print ``Hello World'' from Fortran, one can call it using
2344 @smallexample
2345   use iso_c_binding, only: C_CHAR, C_NULL_CHAR
2346   interface
2347     subroutine print_c(string) bind(C, name="print_C")
2348       use iso_c_binding, only: c_char
2349       character(kind=c_char) :: string(*)
2350     end subroutine print_c
2351   end interface
2352   call print_c(C_CHAR_"Hello World"//C_NULL_CHAR)
2353 @end smallexample
2355 As the example shows, one needs to ensure that the
2356 string is @code{NUL} terminated.  Additionally, the dummy argument
2357 @var{string} of @code{print_C} is a length-one assumed-size
2358 array; using @code{character(len=*)} is not allowed.  The example
2359 above uses @code{c_char_"Hello World"} to ensure the string
2360 literal has the right type; typically the default character
2361 kind and @code{c_char} are the same and thus @code{"Hello World"}
2362 is equivalent.  However, the standard does not guarantee this.
2364 The use of strings is now further illustrated using the C library
2365 function @code{strncpy}, whose prototype is
2367 @smallexample
2368   char *strncpy(char *restrict s1, const char *restrict s2, size_t n);
2369 @end smallexample
2371 The function @code{strncpy} copies at most @var{n} characters from
2372 string @var{s2} to @var{s1} and returns @var{s1}.  In the following
2373 example, we ignore the return value:
2375 @smallexample
2376   use iso_c_binding
2377   implicit none
2378   character(len=30) :: str,str2
2379   interface
2380     ! Ignore the return value of strncpy -> subroutine
2381     ! "restrict" is always assumed if we do not pass a pointer
2382     subroutine strncpy(dest, src, n) bind(C)
2383       import
2384       character(kind=c_char),  intent(out) :: dest(*)
2385       character(kind=c_char),  intent(in)  :: src(*)
2386       integer(c_size_t), value, intent(in) :: n
2387     end subroutine strncpy
2388   end interface
2389   str = repeat('X',30) ! Initialize whole string with 'X'
2390   call strncpy(str, c_char_"Hello World"//C_NULL_CHAR, &
2391                len(c_char_"Hello World",kind=c_size_t))
2392   print '(a)', str ! prints: "Hello WorldXXXXXXXXXXXXXXXXXXX"
2393   end
2394 @end smallexample
2396 The intrinsic procedures are described in @ref{Intrinsic Procedures}.
2398 @node Working with Pointers
2399 @subsection Working with Pointers
2401 C pointers are represented in Fortran via the special opaque derived type
2402 @code{type(c_ptr)} (with private components).  Thus one needs to
2403 use intrinsic conversion procedures to convert from or to C pointers.
2404 For example,
2406 @smallexample
2407   use iso_c_binding
2408   type(c_ptr) :: cptr1, cptr2
2409   integer, target :: array(7), scalar
2410   integer, pointer :: pa(:), ps
2411   cptr1 = c_loc(array(1)) ! The programmer needs to ensure that the
2412                           ! array is contiguous if required by the C
2413                           ! procedure
2414   cptr2 = c_loc(scalar)
2415   call c_f_pointer(cptr2, ps)
2416   call c_f_pointer(cptr2, pa, shape=[7])
2417 @end smallexample
2419 When converting C to Fortran arrays, the one-dimensional @code{SHAPE} argument
2420 has to be passed.
2422 If a pointer is a dummy-argument of an interoperable procedure, it usually
2423 has to be declared using the @code{VALUE} attribute.  @code{void*}
2424 matches @code{TYPE(C_PTR), VALUE}, while @code{TYPE(C_PTR)} alone
2425 matches @code{void**}.
2427 Procedure pointers are handled analogously to pointers; the C type is
2428 @code{TYPE(C_FUNPTR)} and the intrinsic conversion procedures are
2429 @code{C_F_PROCPOINTER} and @code{C_FUNLOC}.
2431 Let us consider two examples of actually passing a procedure pointer from
2432 C to Fortran and vice versa.  Note that these examples are also very
2433 similar to passing ordinary pointers between both languages. First,
2434 consider this code in C:
2436 @smallexample
2437 /* Procedure implemented in Fortran.  */
2438 void get_values (void (*)(double));
2440 /* Call-back routine we want called from Fortran.  */
2441 void
2442 print_it (double x)
2444   printf ("Number is %f.\n", x);
2447 /* Call Fortran routine and pass call-back to it.  */
2448 void
2449 foobar ()
2451   get_values (&print_it);
2453 @end smallexample
2455 A matching implementation for @code{get_values} in Fortran, that correctly
2456 receives the procedure pointer from C and is able to call it, is given
2457 in the following @code{MODULE}:
2459 @smallexample
2460 MODULE m
2461   IMPLICIT NONE
2463   ! Define interface of call-back routine.
2464   ABSTRACT INTERFACE
2465     SUBROUTINE callback (x)
2466       USE, INTRINSIC :: ISO_C_BINDING
2467       REAL(KIND=C_DOUBLE), INTENT(IN), VALUE :: x
2468     END SUBROUTINE callback
2469   END INTERFACE
2471 CONTAINS
2473   ! Define C-bound procedure.
2474   SUBROUTINE get_values (cproc) BIND(C)
2475     USE, INTRINSIC :: ISO_C_BINDING
2476     TYPE(C_FUNPTR), INTENT(IN), VALUE :: cproc
2478     PROCEDURE(callback), POINTER :: proc
2480     ! Convert C to Fortran procedure pointer.
2481     CALL C_F_PROCPOINTER (cproc, proc)
2483     ! Call it.
2484     CALL proc (1.0_C_DOUBLE)
2485     CALL proc (-42.0_C_DOUBLE)
2486     CALL proc (18.12_C_DOUBLE)
2487   END SUBROUTINE get_values
2489 END MODULE m
2490 @end smallexample
2492 Next, we want to call a C routine that expects a procedure pointer argument
2493 and pass it a Fortran procedure (which clearly must be interoperable!).
2494 Again, the C function may be:
2496 @smallexample
2498 call_it (int (*func)(int), int arg)
2500   return func (arg);
2502 @end smallexample
2504 It can be used as in the following Fortran code:
2506 @smallexample
2507 MODULE m
2508   USE, INTRINSIC :: ISO_C_BINDING
2509   IMPLICIT NONE
2511   ! Define interface of C function.
2512   INTERFACE
2513     INTEGER(KIND=C_INT) FUNCTION call_it (func, arg) BIND(C)
2514       USE, INTRINSIC :: ISO_C_BINDING
2515       TYPE(C_FUNPTR), INTENT(IN), VALUE :: func
2516       INTEGER(KIND=C_INT), INTENT(IN), VALUE :: arg
2517     END FUNCTION call_it
2518   END INTERFACE
2520 CONTAINS
2522   ! Define procedure passed to C function.
2523   ! It must be interoperable!
2524   INTEGER(KIND=C_INT) FUNCTION double_it (arg) BIND(C)
2525     INTEGER(KIND=C_INT), INTENT(IN), VALUE :: arg
2526     double_it = arg + arg
2527   END FUNCTION double_it
2529   ! Call C function.
2530   SUBROUTINE foobar ()
2531     TYPE(C_FUNPTR) :: cproc
2532     INTEGER(KIND=C_INT) :: i
2534     ! Get C procedure pointer.
2535     cproc = C_FUNLOC (double_it)
2537     ! Use it.
2538     DO i = 1_C_INT, 10_C_INT
2539       PRINT *, call_it (cproc, i)
2540     END DO
2541   END SUBROUTINE foobar
2543 END MODULE m
2544 @end smallexample
2546 @node Further Interoperability of Fortran with C
2547 @subsection Further Interoperability of Fortran with C
2549 Assumed-shape and allocatable arrays are passed using an array descriptor
2550 (dope vector).  The internal structure of the array descriptor used
2551 by GNU Fortran is not yet documented and will change.  There will also be
2552 a Technical Specification (TS 29113) which standardizes an interoperable
2553 array descriptor.  Until then, you can use the Chasm Language
2554 Interoperability Tools, @url{http://chasm-interop.sourceforge.net/},
2555 which provide an interface to GNU Fortran's array descriptor.
2557 GNU Fortran already supports the C-interoperable @code{OPTIONAL}
2558 attribute; for absent arguments, a @code{NULL} pointer is passed.
2562 @node GNU Fortran Compiler Directives
2563 @section GNU Fortran Compiler Directives
2565 The Fortran standard describes how a conforming program shall
2566 behave; however, the exact implementation is not standardized.  In order
2567 to allow the user to choose specific implementation details, compiler
2568 directives can be used to set attributes of variables and procedures
2569 which are not part of the standard.  Whether a given attribute is
2570 supported and its exact effects depend on both the operating system and
2571 on the processor; see
2572 @ref{Top,,C Extensions,gcc,Using the GNU Compiler Collection (GCC)}
2573 for details.
2575 For procedures and procedure pointers, the following attributes can
2576 be used to change the calling convention:
2578 @itemize
2579 @item @code{CDECL} -- standard C calling convention
2580 @item @code{STDCALL} -- convention where the called procedure pops the stack
2581 @item @code{FASTCALL} -- part of the arguments are passed via registers
2582 instead using the stack
2583 @end itemize
2585 Besides changing the calling convention, the attributes also influence
2586 the decoration of the symbol name, e.g., by a leading underscore or by
2587 a trailing at-sign followed by the number of bytes on the stack.  When
2588 assigning a procedure to a procedure pointer, both should use the same
2589 calling convention.
2591 On some systems, procedures and global variables (module variables and
2592 @code{COMMON} blocks) need special handling to be accessible when they
2593 are in a shared library.  The following attributes are available:
2595 @itemize
2596 @item @code{DLLEXPORT} -- provide a global pointer to a pointer in the DLL
2597 @item @code{DLLIMPORT} -- reference the function or variable using a global pointer 
2598 @end itemize
2600 The attributes are specified using the syntax
2602 @code{!GCC$ ATTRIBUTES} @var{attribute-list} @code{::} @var{variable-list}
2604 where in free-form source code only whitespace is allowed before @code{!GCC$}
2605 and in fixed-form source code @code{!GCC$}, @code{cGCC$} or @code{*GCC$} shall
2606 start in the first column.
2608 For procedures, the compiler directives shall be placed into the body
2609 of the procedure; for variables and procedure pointers, they shall be in
2610 the same declaration part as the variable or procedure pointer.
2614 @node Non-Fortran Main Program
2615 @section Non-Fortran Main Program
2617 @menu
2618 * _gfortran_set_args:: Save command-line arguments
2619 * _gfortran_set_options:: Set library option flags
2620 * _gfortran_set_convert:: Set endian conversion
2621 * _gfortran_set_record_marker:: Set length of record markers
2622 * _gfortran_set_max_subrecord_length:: Set subrecord length
2623 * _gfortran_set_fpe:: Set when a Floating Point Exception should be raised
2624 @end menu
2626 Even if you are doing mixed-language programming, it is very
2627 likely that you do not need to know or use the information in this
2628 section.  Since it is about the internal structure of GNU Fortran,
2629 it may also change in GCC minor releases.
2631 When you compile a @code{PROGRAM} with GNU Fortran, a function
2632 with the name @code{main} (in the symbol table of the object file)
2633 is generated, which initializes the libgfortran library and then
2634 calls the actual program which uses the name @code{MAIN__}, for
2635 historic reasons.  If you link GNU Fortran compiled procedures
2636 to, e.g., a C or C++ program or to a Fortran program compiled by
2637 a different compiler, the libgfortran library is not initialized
2638 and thus a few intrinsic procedures do not work properly, e.g.
2639 those for obtaining the command-line arguments.
2641 Therefore, if your @code{PROGRAM} is not compiled with
2642 GNU Fortran and the GNU Fortran compiled procedures require
2643 intrinsics relying on the library initialization, you need to
2644 initialize the library yourself.  Using the default options,
2645 gfortran calls @code{_gfortran_set_args} and
2646 @code{_gfortran_set_options}.  The initialization of the former
2647 is needed if the called procedures access the command line
2648 (and for backtracing); the latter sets some flags based on the
2649 standard chosen or to enable backtracing.  In typical programs,
2650 it is not necessary to call any initialization function.
2652 If your @code{PROGRAM} is compiled with GNU Fortran, you shall
2653 not call any of the following functions.  The libgfortran
2654 initialization functions are shown in C syntax but using C
2655 bindings they are also accessible from Fortran.
2658 @node _gfortran_set_args
2659 @subsection @code{_gfortran_set_args} --- Save command-line arguments
2660 @fnindex _gfortran_set_args
2661 @cindex libgfortran initialization, set_args
2663 @table @asis
2664 @item @emph{Description}:
2665 @code{_gfortran_set_args} saves the command-line arguments; this
2666 initialization is required if any of the command-line intrinsics
2667 is called.  Additionally, it shall be called if backtracing is
2668 enabled (see @code{_gfortran_set_options}).
2670 @item @emph{Syntax}:
2671 @code{void _gfortran_set_args (int argc, char *argv[])}
2673 @item @emph{Arguments}:
2674 @multitable @columnfractions .15 .70
2675 @item @var{argc} @tab number of command line argument strings
2676 @item @var{argv} @tab the command-line argument strings; argv[0]
2677 is the pathname of the executable itself.
2678 @end multitable
2680 @item @emph{Example}:
2681 @smallexample
2682 int main (int argc, char *argv[])
2684   /* Initialize libgfortran.  */
2685   _gfortran_set_args (argc, argv);
2686   return 0;
2688 @end smallexample
2689 @end table
2692 @node _gfortran_set_options
2693 @subsection @code{_gfortran_set_options} --- Set library option flags
2694 @fnindex _gfortran_set_options
2695 @cindex libgfortran initialization, set_options
2697 @table @asis
2698 @item @emph{Description}:
2699 @code{_gfortran_set_options} sets several flags related to the Fortran
2700 standard to be used, whether backtracing should be enabled
2701 and whether range checks should be performed.  The syntax allows for
2702 upward compatibility since the number of passed flags is specified; for
2703 non-passed flags, the default value is used.  See also
2704 @pxref{Code Gen Options}.  Please note that not all flags are actually
2705 used.
2707 @item @emph{Syntax}:
2708 @code{void _gfortran_set_options (int num, int options[])}
2710 @item @emph{Arguments}:
2711 @multitable @columnfractions .15 .70
2712 @item @var{num} @tab number of options passed
2713 @item @var{argv} @tab The list of flag values
2714 @end multitable
2716 @item @emph{option flag list}:
2717 @multitable @columnfractions .15 .70
2718 @item @var{option}[0] @tab Allowed standard; can give run-time errors
2719 if e.g. an input-output edit descriptor is invalid in a given standard.
2720 Possible values are (bitwise or-ed) @code{GFC_STD_F77} (1),
2721 @code{GFC_STD_F95_OBS} (2), @code{GFC_STD_F95_DEL} (4), @code{GFC_STD_F95}
2722 (8), @code{GFC_STD_F2003} (16), @code{GFC_STD_GNU} (32),
2723 @code{GFC_STD_LEGACY} (64), @code{GFC_STD_F2008} (128), 
2724 @code{GFC_STD_F2008_OBS} (256) and GFC_STD_F2008_TS (512). Default:
2725 @code{GFC_STD_F95_OBS | GFC_STD_F95_DEL | GFC_STD_F95 | GFC_STD_F2003
2726 | GFC_STD_F2008 | GFC_STD_F2008_TS | GFC_STD_F2008_OBS | GFC_STD_F77
2727 | GFC_STD_GNU | GFC_STD_LEGACY}.
2728 @item @var{option}[1] @tab Standard-warning flag; prints a warning to
2729 standard error.  Default: @code{GFC_STD_F95_DEL | GFC_STD_LEGACY}.
2730 @item @var{option}[2] @tab If non zero, enable pedantic checking.
2731 Default: off.
2732 @item @var{option}[3] @tab Unused.
2733 @item @var{option}[4] @tab If non zero, enable backtracing on run-time
2734 errors.  Default: off.
2735 Note: Installs a signal handler and requires command-line
2736 initialization using @code{_gfortran_set_args}.
2737 @item @var{option}[5] @tab If non zero, supports signed zeros.
2738 Default: enabled.
2739 @item @var{option}[6] @tab Enables run-time checking.  Possible values
2740 are (bitwise or-ed): GFC_RTCHECK_BOUNDS (1), GFC_RTCHECK_ARRAY_TEMPS (2),
2741 GFC_RTCHECK_RECURSION (4), GFC_RTCHECK_DO (16), GFC_RTCHECK_POINTER (32).
2742 Default: disabled.
2743 @item @var{option}[7] @tab If non zero, range checking is enabled.
2744 Default: enabled.  See -frange-check (@pxref{Code Gen Options}).
2745 @end multitable
2747 @item @emph{Example}:
2748 @smallexample
2749   /* Use gfortran 4.7 default options.  */
2750   static int options[] = @{68, 511, 0, 0, 1, 1, 0, 1@};
2751   _gfortran_set_options (8, &options);
2752 @end smallexample
2753 @end table
2756 @node _gfortran_set_convert
2757 @subsection @code{_gfortran_set_convert} --- Set endian conversion
2758 @fnindex _gfortran_set_convert
2759 @cindex libgfortran initialization, set_convert
2761 @table @asis
2762 @item @emph{Description}:
2763 @code{_gfortran_set_convert} set the representation of data for
2764 unformatted files.
2766 @item @emph{Syntax}:
2767 @code{void _gfortran_set_convert (int conv)}
2769 @item @emph{Arguments}:
2770 @multitable @columnfractions .15 .70
2771 @item @var{conv} @tab Endian conversion, possible values:
2772 GFC_CONVERT_NATIVE (0, default), GFC_CONVERT_SWAP (1),
2773 GFC_CONVERT_BIG (2), GFC_CONVERT_LITTLE (3).
2774 @end multitable
2776 @item @emph{Example}:
2777 @smallexample
2778 int main (int argc, char *argv[])
2780   /* Initialize libgfortran.  */
2781   _gfortran_set_args (argc, argv);
2782   _gfortran_set_convert (1);
2783   return 0;
2785 @end smallexample
2786 @end table
2789 @node _gfortran_set_record_marker
2790 @subsection @code{_gfortran_set_record_marker} --- Set length of record markers
2791 @fnindex _gfortran_set_record_marker
2792 @cindex libgfortran initialization, set_record_marker
2794 @table @asis
2795 @item @emph{Description}:
2796 @code{_gfortran_set_record_marker} sets the length of record markers
2797 for unformatted files.
2799 @item @emph{Syntax}:
2800 @code{void _gfortran_set_record_marker (int val)}
2802 @item @emph{Arguments}:
2803 @multitable @columnfractions .15 .70
2804 @item @var{val} @tab Length of the record marker; valid values
2805 are 4 and 8.  Default is 4.
2806 @end multitable
2808 @item @emph{Example}:
2809 @smallexample
2810 int main (int argc, char *argv[])
2812   /* Initialize libgfortran.  */
2813   _gfortran_set_args (argc, argv);
2814   _gfortran_set_record_marker (8);
2815   return 0;
2817 @end smallexample
2818 @end table
2821 @node _gfortran_set_fpe
2822 @subsection @code{_gfortran_set_fpe} --- Enable floating point exception traps
2823 @fnindex _gfortran_set_fpe
2824 @cindex libgfortran initialization, set_fpe
2826 @table @asis
2827 @item @emph{Description}:
2828 @code{_gfortran_set_fpe} enables floating point exception traps for
2829 the specified exceptions.  On most systems, this will result in a
2830 SIGFPE signal being sent and the program being aborted.
2832 @item @emph{Syntax}:
2833 @code{void _gfortran_set_fpe (int val)}
2835 @item @emph{Arguments}:
2836 @multitable @columnfractions .15 .70
2837 @item @var{option}[0] @tab IEEE exceptions.  Possible values are
2838 (bitwise or-ed) zero (0, default) no trapping,
2839 @code{GFC_FPE_INVALID} (1), @code{GFC_FPE_DENORMAL} (2),
2840 @code{GFC_FPE_ZERO} (4), @code{GFC_FPE_OVERFLOW} (8),
2841 @code{GFC_FPE_UNDERFLOW} (16), and @code{GFC_FPE_INEXACT} (32).
2842 @end multitable
2844 @item @emph{Example}:
2845 @smallexample
2846 int main (int argc, char *argv[])
2848   /* Initialize libgfortran.  */
2849   _gfortran_set_args (argc, argv);
2850   /* FPE for invalid operations such as SQRT(-1.0).  */
2851   _gfortran_set_fpe (1);
2852   return 0;
2854 @end smallexample
2855 @end table
2858 @node _gfortran_set_max_subrecord_length
2859 @subsection @code{_gfortran_set_max_subrecord_length} --- Set subrecord length
2860 @fnindex _gfortran_set_max_subrecord_length
2861 @cindex libgfortran initialization, set_max_subrecord_length
2863 @table @asis
2864 @item @emph{Description}:
2865 @code{_gfortran_set_max_subrecord_length} set the maximum length
2866 for a subrecord.  This option only makes sense for testing and
2867 debugging of unformatted I/O.
2869 @item @emph{Syntax}:
2870 @code{void _gfortran_set_max_subrecord_length (int val)}
2872 @item @emph{Arguments}:
2873 @multitable @columnfractions .15 .70
2874 @item @var{val} @tab the maximum length for a subrecord;
2875 the maximum permitted value is 2147483639, which is also
2876 the default.
2877 @end multitable
2879 @item @emph{Example}:
2880 @smallexample
2881 int main (int argc, char *argv[])
2883   /* Initialize libgfortran.  */
2884   _gfortran_set_args (argc, argv);
2885   _gfortran_set_max_subrecord_length (8);
2886   return 0;
2888 @end smallexample
2889 @end table
2893 @c Intrinsic Procedures
2894 @c ---------------------------------------------------------------------
2896 @include intrinsic.texi
2899 @tex
2900 \blankpart
2901 @end tex
2903 @c ---------------------------------------------------------------------
2904 @c Contributing
2905 @c ---------------------------------------------------------------------
2907 @node Contributing
2908 @unnumbered Contributing
2909 @cindex Contributing
2911 Free software is only possible if people contribute to efforts
2912 to create it.
2913 We're always in need of more people helping out with ideas
2914 and comments, writing documentation and contributing code.
2916 If you want to contribute to GNU Fortran,
2917 have a look at the long lists of projects you can take on.
2918 Some of these projects are small,
2919 some of them are large;
2920 some are completely orthogonal to the rest of what is
2921 happening on GNU Fortran,
2922 but others are ``mainstream'' projects in need of enthusiastic hackers.
2923 All of these projects are important!
2924 We will eventually get around to the things here,
2925 but they are also things doable by someone who is willing and able.
2927 @menu
2928 * Contributors::
2929 * Projects::
2930 * Proposed Extensions::
2931 @end menu
2934 @node Contributors
2935 @section Contributors to GNU Fortran
2936 @cindex Contributors
2937 @cindex Credits
2938 @cindex Authors
2940 Most of the parser was hand-crafted by @emph{Andy Vaught}, who is
2941 also the initiator of the whole project.  Thanks Andy!
2942 Most of the interface with GCC was written by @emph{Paul Brook}.
2944 The following individuals have contributed code and/or
2945 ideas and significant help to the GNU Fortran project
2946 (in alphabetical order):
2948 @itemize @minus
2949 @item Janne Blomqvist
2950 @item Steven Bosscher
2951 @item Paul Brook
2952 @item Tobias Burnus
2953 @item Fran@,{c}ois-Xavier Coudert
2954 @item Bud Davis
2955 @item Jerry DeLisle
2956 @item Erik Edelmann
2957 @item Bernhard Fischer
2958 @item Daniel Franke
2959 @item Richard Guenther
2960 @item Richard Henderson
2961 @item Katherine Holcomb
2962 @item Jakub Jelinek
2963 @item Niels Kristian Bech Jensen
2964 @item Steven Johnson
2965 @item Steven G. Kargl
2966 @item Thomas Koenig
2967 @item Asher Langton
2968 @item H. J. Lu
2969 @item Toon Moene
2970 @item Brooks Moses
2971 @item Andrew Pinski
2972 @item Tim Prince
2973 @item Christopher D. Rickett
2974 @item Richard Sandiford
2975 @item Tobias Schl@"uter
2976 @item Roger Sayle
2977 @item Paul Thomas
2978 @item Andy Vaught
2979 @item Feng Wang
2980 @item Janus Weil
2981 @item Daniel Kraft
2982 @end itemize
2984 The following people have contributed bug reports,
2985 smaller or larger patches,
2986 and much needed feedback and encouragement for the
2987 GNU Fortran project: 
2989 @itemize @minus
2990 @item Bill Clodius
2991 @item Dominique d'Humi@`eres
2992 @item Kate Hedstrom
2993 @item Erik Schnetter
2994 @item Joost VandeVondele
2995 @end itemize
2997 Many other individuals have helped debug,
2998 test and improve the GNU Fortran compiler over the past few years,
2999 and we welcome you to do the same!
3000 If you already have done so,
3001 and you would like to see your name listed in the
3002 list above, please contact us.
3005 @node Projects
3006 @section Projects
3008 @table @emph
3010 @item Help build the test suite
3011 Solicit more code for donation to the test suite: the more extensive the
3012 testsuite, the smaller the risk of breaking things in the future! We can
3013 keep code private on request.
3015 @item Bug hunting/squishing
3016 Find bugs and write more test cases! Test cases are especially very
3017 welcome, because it allows us to concentrate on fixing bugs instead of
3018 isolating them.  Going through the bugzilla database at
3019 @url{http://gcc.gnu.org/@/bugzilla/} to reduce testcases posted there and
3020 add more information (for example, for which version does the testcase
3021 work, for which versions does it fail?) is also very helpful.
3023 @end table
3026 @node Proposed Extensions
3027 @section Proposed Extensions
3029 Here's a list of proposed extensions for the GNU Fortran compiler, in no particular
3030 order.  Most of these are necessary to be fully compatible with
3031 existing Fortran compilers, but they are not part of the official
3032 J3 Fortran 95 standard.
3034 @subsection Compiler extensions: 
3035 @itemize @bullet
3036 @item
3037 User-specified alignment rules for structures.
3039 @item
3040 Automatically extend single precision constants to double.
3042 @item
3043 Compile code that conserves memory by dynamically allocating common and
3044 module storage either on stack or heap.
3046 @item
3047 Compile flag to generate code for array conformance checking (suggest -CC).
3049 @item
3050 User control of symbol names (underscores, etc).
3052 @item
3053 Compile setting for maximum size of stack frame size before spilling
3054 parts to static or heap.
3056 @item
3057 Flag to force local variables into static space.
3059 @item
3060 Flag to force local variables onto stack.
3061 @end itemize
3064 @subsection Environment Options
3065 @itemize @bullet
3066 @item
3067 Pluggable library modules for random numbers, linear algebra.
3068 LA should use BLAS calling conventions.
3070 @item
3071 Environment variables controlling actions on arithmetic exceptions like
3072 overflow, underflow, precision loss---Generate NaN, abort, default.
3073 action.
3075 @item
3076 Set precision for fp units that support it (i387).
3078 @item
3079 Variable for setting fp rounding mode.
3081 @item
3082 Variable to fill uninitialized variables with a user-defined bit
3083 pattern.
3085 @item
3086 Environment variable controlling filename that is opened for that unit
3087 number.
3089 @item
3090 Environment variable to clear/trash memory being freed.
3092 @item
3093 Environment variable to control tracing of allocations and frees.
3095 @item
3096 Environment variable to display allocated memory at normal program end.
3098 @item
3099 Environment variable for filename for * IO-unit.
3101 @item
3102 Environment variable for temporary file directory.
3104 @item
3105 Environment variable forcing standard output to be line buffered (unix).
3107 @end itemize
3110 @c ---------------------------------------------------------------------
3111 @c GNU General Public License
3112 @c ---------------------------------------------------------------------
3114 @include gpl_v3.texi
3118 @c ---------------------------------------------------------------------
3119 @c GNU Free Documentation License
3120 @c ---------------------------------------------------------------------
3122 @include fdl.texi
3126 @c ---------------------------------------------------------------------
3127 @c Funding Free Software
3128 @c ---------------------------------------------------------------------
3130 @include funding.texi
3132 @c ---------------------------------------------------------------------
3133 @c Indices
3134 @c ---------------------------------------------------------------------
3136 @node Option Index
3137 @unnumbered Option Index
3138 @command{gfortran}'s command line options are indexed here without any
3139 initial @samp{-} or @samp{--}.  Where an option has both positive and
3140 negative forms (such as -foption and -fno-option), relevant entries in
3141 the manual are indexed under the most appropriate form; it may sometimes
3142 be useful to look up both forms.
3143 @printindex op
3145 @node Keyword Index
3146 @unnumbered Keyword Index
3147 @printindex cp
3149 @bye