GFORTRAN(1)
β¨ NAME β¨
gfortran β the GNU Fortran compiler π (yes, this is GFORTRAN(1), from the GNU project, manual section 1, bestie!)
π SYNOPSIS π
gfortran [-c|-S|-E]
[-g] [-pg] [-Olevel]
[-Wwarn...] [-pedantic]
[-Idir...] [-Ldir...]
[-Dmacro[=defn]...] [-Umacro]
[-foption...]
[-mmachine-option...]
[-o outfile] infile...
Only the most useful options are listed here; see below for the remainder. (Like, the rest are down there, keep scrolling bestie π )
π DESCRIPTION π
Okay so the gfortran command supports all the options that the gcc command supports. But only the options specific to GNU Fortran are documented here. π
All GCC and GNU Fortran options are accepted both by gfortran and by gcc (as well as any other drivers built at the same time, such as g++), because adding GNU Fortran to the GCC distribution enables acceptance of GNU Fortran options by all of the relevant drivers. So like, they all share the love. π«Ά
In some cases, options have positive and negative forms; the negative form of -ffoo would be -fno-foo. This manual documents only one of these two forms, whichever one is not the default. So if you see one, the other exists too, iykyk. π
π οΈ OPTIONS π οΈ
Here's a summary of all the options specific to GNU Fortran, grouped by type. Explanations are in the following sections. π
π Fortran Language Options π
-fall-intrinsics-fallow-argument-mismatch-fallow-invalid-boz-fbackslash-fcray-pointer-fd-lines-as-code-fd-lines-as-comments-fdec-fdec-char-conversions-fdec-structure-fdec-intrinsic-ints-fdec-static-fdec-math-fdec-include-fdec-format-defaults-fdec-blank-format-item-fdefault-double-8-fdefault-integer-8-fdefault-real-8-fdefault-real-10-fdefault-real-16-fdollar-ok-ffixed-line-length-n-ffixed-line-length-none-fpad-source-ffree-form-ffree-line-length-n-ffree-line-length-none-fimplicit-none-finteger-4-integer-8-fmax-identifier-length-fmodule-private-ffixed-form-fno-range-check-fopenacc-fopenmp-freal-4-real-10-freal-4-real-16-freal-4-real-8-freal-8-real-10-freal-8-real-16-freal-8-real-4-std=std-ftest-forall-temp
π Preprocessing Options π
-A-question[=answer]-Aquestion=answer-C-CC-Dmacro[=defn]-H-P-Umacro-cpp-dD-dI-dM-dN-dU-fworking-directory-imultilib dir-iprefix file-iquote-isysroot dir-isystem dir-nocpp-nostdinc-undef
π Error and Warning Options π
-Waliasing-Wall-Wampersand-Warray-bounds-Wc-binding-type-Wcharacter-truncation-Wconversion-Wdo-subscript-Wfunction-elimination-Wimplicit-interface-Wimplicit-procedure-Wintrinsic-shadow-Wuse-without-only-Wintrinsics-std-Wline-truncation-Wno-align-commons-Wno-overwrite-recursive-Wno-tabs-Wreal-q-constant-Wsurprising-Wunderflow-Wunused-parameter-Wrealloc-lhs-Wrealloc-lhs-all-Wfrontend-loop-interchange-Wtarget-lifetime-fmax-errors=n-fsyntax-only-pedantic-pedantic-errors
π Debugging Options π
-fbacktrace-fdump-fortran-optimized-fdump-fortran-original-fdebug-aux-vars-fdump-fortran-global-fdump-parse-tree-ffpe-trap=list-ffpe-summary=list
π Directory Options π
-Idir-Jdir-fintrinsic-modules-path dir
π Link Options π
-static-libgfortran
π Runtime Options π
-fconvert=conversion-fmax-subrecord-length=length-frecord-marker=length-fsign-zero
π Interoperability Options π
-fc-prototypes-fc-prototypes-external
π Code Generation Options π
-faggressive-function-elimination-fblas-matmul-limit=n-fbounds-check-ftail-call-workaround-ftail-call-workaround=n-fcheck-array-temporaries-fcheck=<all|array-temps|bits|bounds|do|mem|pointer|recursion>-fcoarray=<none|single|lib>-fexternal-blas-ff2c-ffrontend-loop-interchange-ffrontend-optimize-finit-character=n-finit-integer=n-finit-local-zero-finit-derived-finit-logical=<true|false>-finit-real=<zero|inf|-inf|nan|snan>-finline-matmul-limit=n-finline-arg-packing-fmax-array-constructor=n-fmax-stack-var-size=n-fno-align-commons-fno-automatic-fno-protect-parens-fno-underscoring-fsecond-underscore-fpack-derived-frealloc-lhs-frecursive-frepack-arrays-fshort-enums-fstack-arrays
π§ Options controlling Fortran dialect π§
The following options control the details of the Fortran dialect accepted by the compiler: π
-ffree-form,-ffixed-formβ Okay so these tell the compiler what layout your source file is in. Free form is the Fortran 90 era vibe, fixed form is the old-school classic. If you don't pick either, the compiler guesses from the file extension. π-fall-intrinsicsβ This makes all intrinsic procedures (including the GNU-specific extensions) get accepted. It's lowkey useful with-std=when you want standard-compliance but still want the full range of intrinsics thatgfortranoffers. But heads up:-Wintrinsics-stdgets ignored, and no user-defined procedure with the same name as any intrinsic will be called unless it's explicitly declaredEXTERNAL. π-fallow-argument-mismatchβ Some code out here has calls to external procedures with mismatches between the calls and the procedure definition, or between different calls. That code is non-conforming and usually gets flagged as an error. This option degrades that error to a warning, and that warning can only be disabled by disabling all warnings via-w. Only a single occurrence per argument gets flagged by this warning.-fallow-argument-mismatchis implied by-std=legacy.
Using this option is strongly discouraged. You can write standard-conforming code that allows different types of arguments by using an explicit interface and TYPE(*). So like, don't do it unless you have to, bestie. π
-fallow-invalid-bozβ A BOZ literal constant can only show up in a limited number of contexts in standard conforming Fortran. This option degrades an error condition to a warning, and lets a BOZ literal constant appear where the Fortran standard would otherwise say no. π«-fd-lines-as-code,-fd-lines-as-commentsβ These enable special treatment for lines beginning withdorDin fixed form sources. With-fd-lines-as-code, those lines are treated as if the first column contained a blank. With-fd-lines-as-comments, they're treated as comment lines. β¨-fdecβ DEC compatibility mode, periodt. It enables extensions and other features that mimic the default behavior of older compilers (like DEC). These features are non-standard and should be avoided at all costs. For details on GNU Fortran's implementation of these extensions, see the full documentation.
Other flags enabled by this switch are: -fdollar-ok -fcray-pointer -fdec-char-conversions -fdec-structure -fdec-intrinsic-ints -fdec-static -fdec-math -fdec-include -fdec-blank-format-item -fdec-format-defaults
If -fd-lines-as-code/-fd-lines-as-comments are unset, then -fdec also sets -fd-lines-as-comments.
-fdec-char-conversionsβ Enables the use of character literals in assignments andDATAstatements for non-character variables. π-fdec-structureβ Enables DECSTRUCTUREandRECORDas well asUNION,MAP, and dot (.) as a member separator (in addition to%). This is for compatibility only; Fortran 90 derived types should be used instead where possible. π-fdec-intrinsic-intsβ Enables B/I/J/K kind variants of existing integer functions (e.g. BIAND, IIAND, JIAND, etc...). For a complete list of intrinsics, see the full documentation. π’-fdec-mathβ Enables legacy math intrinsics such as COTAN and degree-valued trigonometric functions (e.g. TAND, ATAND, etc...) for compatibility with older code. π-fdec-staticβ Enables DEC-style STATIC and AUTOMATIC attributes to explicitly specify the storage of variables and other objects. ποΈ-fdec-includeβ Enables parsing of INCLUDE as a statement in addition to parsing it as INCLUDE line. When parsed as INCLUDE statement, INCLUDE does not have to be on a single line and can use line continuations. π-fdec-format-defaultsβ Enables format specifiers F, G and I to be used without width specifiers; default widths will be used instead. π’-fdec-blank-format-itemβ Enables a blank format item at the end of a format specification, i.e. nothing following the final comma. π³-fdollar-okβ Allows$as a valid non-first character in a symbol name. Symbols that start with$are rejected since it's unclear which rules to apply to implicit typing as different vendors implement different rules. Using$inIMPLICITstatements is also rejected. π²-fbackslashβ Changes the interpretation of backslashes in string literals from a single backslash character to "C-style" escape characters. The following combinations are expanded\a,\b,\f,\n,\r,\t,\v,\\, and\0to the ASCII characters alert, backspace, form feed, newline, carriage return, horizontal tab, vertical tab, backslash, and NUL, respectively. Additionally,\xnn,\unnnn and\Unnnnnnnn (where each n is a hexadecimal digit) are translated into the Unicode characters corresponding to the specified code points. All other combinations of a character preceded by\are unexpanded. π-fmodule-privateβ Sets the default accessibility of module entities toPRIVATE. Use-associated entities will not be accessible unless they're explicitly declared asPUBLIC. π-ffixed-line-length-nβ Sets the column after which characters are ignored in typical fixed-form lines in the source file, and, unless-fno-pad-source, through which spaces are assumed (as if padded to that length) after the ends of short fixed-form lines.
Popular values for n include 72 (the standard and the default), 80 (card image), and 132 (corresponding to "extended-source" options in some popular compilers). n may also be none, meaning that the entire line is meaningful and that continued character constants never have implicit spaces appended to them to fill out the line. -ffixed-line-length-0 means the same thing as -ffixed-line-length-none. π
-fno-pad-sourceβ By default fixed-form lines have spaces assumed (as if padded to that length) after the ends of short fixed-form lines. This is not done either if-ffixed-line-length-0,-ffixed-line-length-noneor if-fno-pad-sourceoption is used. With any of those options, continued character constants never have implicit spaces appended to them to fill out the line. π«-ffree-line-length-nβ sets the column after which characters justβ¦ stop mattering in your typical free-form source lines π . Default is132. Andncan benone, meaning the whole line is meaningful (no cutoff, live your truth). Also-ffree-line-length-0means the exact same thing as-ffree-line-length-none.-fmax-identifier-length=nβ the max identifier length allowed, bestie. Typical values are31(Fortran 95) and63(Fortran 2003 and later).-fimplicit-noneβ no implicit typing allowed unless an explicitIMPLICITstatement overrides it. It's literally the equivalent of slappingimplicit noneat the start of every single procedure. No surprises, no mystery variables, periodt.-fcray-pointerβ enables the Cray pointer extension, which gives you C-like pointer functionality. Retro but iconic π.-fopenaccβ turns on the OpenACC extensions β¨. That includes OpenACC!$accdirectives in free form, plusc$acc,*$accand!$accdirectives in fixed form, plus!$conditional compilation sentinels in free form andc$,*$and!$sentinels in fixed form β and when you're linking, it arranges for the OpenACC runtime library to get linked in too.-fopenmpβ turns on the OpenMP extensions π. That includes OpenMP!$ompdirectives in free form, plusc$omp,*$ompand!$ompdirectives in fixed form, plus!$conditional compilation sentinels in free form andc$,*$and!$sentinels in fixed form β and when linking, it arranges for the OpenMP runtime library to be linked in. Also, heads up:-fopenmpimplies-frecursive.-fno-range-checkβ disables range checking on the results of simplifying constant expressions during compilation. Example: GNU Fortran will throw a compile-time error when simplifyinga = 1. / 0. With this option, no error, andajust gets assigned the value+Infinity. And if an expression evaluates to something outside the relevant range of["-HUGE()":HUGE()], the expression gets replaced by-Infor+Infas appropriate. Same energy withDATA i/Z'FFFFFFFF'/β that'll integer-overflow on most systems, but with-fno-range-checkthe value just "wraps around" andigets initialized to-1instead. Chaos, but documented chaos π.-fdefault-integer-8β sets the default integer and logical types to an 8 byte wide type. This also affects the kind of integer constants like42. Unlike-finteger-4-integer-8, it does not promote variables with explicit kind declaration. Know the difference, iykyk.-fdefault-real-8β sets the default real type to an 8 byte wide type. This also affects the kind of non-double real constants like1.0. It promotes the default width ofDOUBLE PRECISIONand double real constants like1.d0to 16 bytes if possible. If-fdefault-double-8is given along withfdefault-real-8, thenDOUBLE PRECISIONand double real constants are not promoted. And unlike-freal-4-real-8,fdefault-real-8does not promote variables with explicit kind declarations.-fdefault-real-10β sets the default real type to an 10 byte wide type (yes, "an 10", we don't gatekeep grammar here π«Ά). This also affects the kind of non-double real constants like1.0. It promotes the default width ofDOUBLE PRECISIONand double real constants like1.d0to 16 bytes if possible. If-fdefault-double-8is given along with-fdefault-real-10, thenDOUBLE PRECISIONand double real constants are not promoted. Unlike-freal-4-real-10,fdefault-real-10does not promote variables with explicit kind declarations.-fdefault-real-16β sets the default real type to an 16 byte wide type. This also affects the kind of non-double real constants like1.0. It promotes the default width ofDOUBLE PRECISIONand double real constants like1.d0to 16 bytes if possible. If-fdefault-double-8is given along with-fdefault-real-16, thenDOUBLE PRECISIONand double real constants are not promoted. Unlike-freal-4-real-16,fdefault-real-16does not promote variables with explicit kind declarations.-fdefault-double-8β sets theDOUBLE PRECISIONtype and double real constants like1.d0to an 8 byte wide type. Does literally nothing if that's already the default. This option prevents-fdefault-real-8,-fdefault-real-10, and-fdefault-real-16from promotingDOUBLE PRECISIONand double real constants like1.d0to 16 bytes.-finteger-4-integer-8β promotes allINTEGER(KIND=4)entities toINTEGER(KIND=8)entities. IfKIND=8isn't available, you get an error, sorry bestie. Use this one with care and it may not be suitable for your codes. Areas of possible concern include calls to external procedures, alignment inEQUIVALENCEand/orCOMMON, generic interfaces, BOZ literal constant conversion, and I/O. Inspection of the intermediate representation of the translated Fortran code, produced by-fdump-tree-original, is suggested π.-freal-4-real-8-freal-4-real-10-freal-4-real-16-freal-8-real-4-freal-8-real-10-freal-8-real-16β these promote allREAL(KIND=M)entities toREAL(KIND=N)entities. IfREAL(KIND=N)isn't available, an error gets issued. The-freal-4-flags also affect the default real kind, and the-freal-8-flags also affect the double-precision real kind. All other real-kind types are unaffected by this option. The promotion is also applied to real literal constants of default and double-precision kind and a specified kind number of 4 or 8, respectively. However,-fdefault-real-8,-fdefault-real-10,-fdefault-real-10, and-fdefault-double-8take precedence for the default and double-precision real kinds, both for real literal constants and for declarations without a kind number. Note that forREAL(KIND=KIND(1.0))the literal may get promoted and then the result may get promoted again β double promotion, main character energy β¨. These options should be used with care and may not be suitable for your codes. Areas of possible concern include calls to external procedures, alignment inEQUIVALENCEand/orCOMMON, generic interfaces, BOZ literal constant conversion, and I/O and calls to intrinsic procedures when passing a value to thekind=dummy argument. Inspection of the intermediate representation of the translated Fortran code, produced by-fdump-fortran-originalor-fdump-tree-original, is suggested.-std=stdβ specifies the standard your program is expected to conform to, which may be one off95,f2003,f2008,f2018,gnu, orlegacy. The default value for std isgnu, which specifies a superset of the latest Fortran standard that includes all of the extensions supported by GNU Fortran β although warnings will be given for obsolete extensions not recommended for use in new code. Thelegacyvalue is equivalent but without the warnings for obsolete extensions, and may be useful for old non-standard programs. Thef95,f2003,f2008, andf2018values specify strict conformance to the Fortran 95, Fortran 2003, Fortran 2008 and Fortran 2018 standards, respectively; errors are given for all extensions beyond the relevant language standard, and warnings are given for the Fortran 77 features that are permitted but obsolescent in later standards. And btw, the deprecated option-std=f2008tsacts as an alias for-std=f2018β it's only there for backwards compatibility with earlier gfortran versions and should not be used any more, okay? It's giving retired π.-ftest-forall-tempβ enhances test coverage by forcing most forall assignments to use temporary. Testing arc, slay π§ͺ.
β¨ Enable and customize preprocessing β¨
Okay so this whole vibe: a lot of Fortran compilers β GNU Fortran included β let you pass the source code through a C preprocessor (CPP; sometimes also called the Fortran preprocessor, FPP) so you can do conditional compilation π. In GNU Fortran's case, it's the GNU C Preprocessor running in traditional mode.
On systems with case-preserving file names, the preprocessor is automatically invoked if the filename extension is .F, .FOR, .FTN, .fpp, .FPP, .F90, .F95, .F03 or .F08. To manually invoke the preprocessor on any file, use -cpp. To disable preprocessing on files where the preprocessor runs automatically, use -nocpp.
If a preprocessed file includes another file with the Fortran INCLUDE statement, the included file is not preprocessed. To preprocess included files, use the equivalent preprocessor statement #include.
If GNU Fortran invokes the preprocessor, __GFORTRAN__ is defined. And you can use the macros __GNUC__, __GNUC_MINOR__ and __GNUC_PATCHLEVEL__ to figure out the version of the compiler π. See Top,,Overview,cpp,The C Preprocessor for details.
GNU Fortran supports a bunch of INTEGER and REAL kind types on top of the kind types required by the Fortran standard β the availability of any given kind type is architecture dependent, no cap. These pre-defined preprocessor macros can be used to conditionally include code for these additional kind types: __GFC_INT_1__, __GFC_INT_2__, __GFC_INT_8__, __GFC_INT_16__, __GFC_REAL_10__, and __GFC_REAL_16__ β.
While CPP is the de-facto standard for preprocessing Fortran code, Part 3 of the Fortran 95 standard (ISO/IEC 1539-3:1998) defines Conditional Compilation β which is not widely used and not directly supported by the GNU Fortran compiler. You can use the program coco to preprocess such files (http://www.daniellnagle.com/coco.html).
The following options control preprocessing of Fortran code:
-cpp-nocppβ enable preprocessing π. The preprocessor is automatically invoked if the file extension is.fpp,.FPP,.F,.FOR,.FTN,.F90,.F95,.F03or.F08. Use this option to manually enable preprocessing of any kind of Fortran file.
To disable preprocessing of files with any of the above listed extensions, use the negative form: -nocpp.
The preprocessor is run in traditional mode. Any restrictions of the file-format, especially the limits on line length, apply for preprocessed output as well, so it might be advisable to use the -ffree-line-length-none or -ffixed-line-length-none options.
-dMβ instead of the normal output, generate a list of'#define'directives for all the macros defined during the execution of the preprocessor, including predefined macros. This gives you a way of finding out what is predefined in your version of the preprocessor π. Assuming you have no filefoo.f90, the command
touch foo.f90; gfortran -cpp -E -dM foo.f90
will show all the predefined macros. Iconic detective work πβ¨.
-dDβ it's giving-dMenergy except for two lil' plot twists: it does not include the predefined macros, and it outputs both the"#define"directives and the result of preprocessing. Both kinds of output go to the standard output file. π-dNβ same vibe as-dD, but it only emits the macro names, not their expansions. Name-drop only, no lore.-dUβ like-dDexcept that only macros that are expanded, or whose definedness is tested in preprocessor directives, get output. The output is delayed until the use or test of the macro, and'#undef'directives are also output for macros tested but undefined at the time. It's the "we'll deal with it when it comes up" option fr.-dIβ outputs'#include'directives in addition to the result of preprocessing. Extra receipts. π§Ύ-fworking-directoryβ enables generation of linemarkers in the preprocessor output that will let the compiler know the current working directory at the time of preprocessing. When this option is enabled, the preprocessor will emit, after the initial linemarker, a second linemarker with the current working directory followed by two slashes. GCC will use this directory, when it is present in the preprocessed input, as the directory emitted as the current working directory in some debugging information formats. This option is implicitly enabled if debugging information is enabled, but this can be inhibited with the negated form-fno-working-directory. If the-Pflag is present in the command line, this option has no effect, since no"#line"directives are emitted whatsoever. So likeβ¦ if-Pis there, this whole thing is cancelled. π-idirafterdir β search dir for include files, but do it after all directories specified with-Iand the standard system directories have been exhausted. dir is treated as a system include directory. If dir begins with"=", then the"="will be replaced by the sysroot prefix; see--sysrootand-isysroot. Basically: last in line, bestie. π«Ά-imultilibdir β use dir as a subdirectory of the directory containing target-specific C++ headers.-iprefixprefix β specify prefix as the prefix for subsequent-iwithprefixoptions. If the prefix represents a directory, you should include the final'/'. Don't forget the slash, it's the little details that slay. β¨-isysrootdir β this option is like the--sysrootoption, but applies only to header files. See the--sysrootoption for more information.-iquotedir β search dir only for header files requested with"#include "file""; they are not searched for"#include <file>", before all directories specified by-Iand before the standard system directories. If dir begins with"=", then the"="will be replaced by the sysroot prefix; see--sysrootand-isysroot. Quote-includes only, no angle brackets allowed, gatekeeping era. πͺ-isystemdir β search dir for header files, after all directories specified by-Ibut before the standard system directories. Mark it as a system directory, so that it gets the same special treatment as is applied to the standard system directories. If dir begins with"=", then the"="will be replaced by the sysroot prefix; see--sysrootand-isysroot.-nostdincβ do not search the standard system directories for header files. Only the directories you have specified with-Ioptions (and the directory of the current file, if appropriate) are searched. Going off-grid, no system directories invited to the party. π-undefβ do not predefine any system-specific or GCC-specific macros. The standard predefined macros remain defined though, those ones stay. π-Apredicate=answerβ make an assertion with the predicate predicate and answer answer. This form is preferred to the older form-A predicate(answer), which is still supported, because it does not use shell special characters. New form is the moment, old form is still here for the OGs.-A-predicate=answerβ cancel an assertion with the predicate predicate and answer answer. Undoing what you did, we love a self-aware queen.-Cβ do not discard comments. All comments are passed through to the output file, except for comments in processed directives, which are deleted along with the directive.
You should be prepared for side effects when using -C; it causes the preprocessor to treat comments as tokens in their own right. For example, comments appearing at the start of what would be a directive line have the effect of turning that line into an ordinary source line, since the first token on the line is no longer a '#'.
Warning: this currently handles C-Style comments only. The preprocessor does not yet recognize Fortran-style comments. π so be careful bestie.
-CCβ do not discard comments, including during macro expansion. This is like-C, except that comments contained within macros are also passed through to the output file where the macro is expanded.
In addition to the side-effects of the -C option, the -CC option causes all C++-style comments inside a macro to be converted to C-style comments. This is to prevent later use of that macro from inadvertently commenting out the remainder of the source line. The -CC option is generally used to support lint comments.
Warning: this currently handles C- and C++-Style comments only. The preprocessor does not yet recognize Fortran-style comments. Same caveat, same energy. π
-Dnameβ predefine name as a macro, with definition1. Simple as that, no notes.-Dname=definitionβ the contents of definition are tokenized and processed as if they appeared during translation phase three in a'#define'directive. In particular, the definition will be truncated by embedded newline characters.
If you are invoking the preprocessor from a shell or shell-like program you may need to use the shell's quoting syntax to protect characters such as spaces that have a meaning in the shell syntax.
If you wish to define a function-like macro on the command line, write its argument list with surrounding parentheses before the equals sign (if any). Parentheses are meaningful to most shells, so you will need to quote the option. With sh and csh, "-D'name(args...)=definition'" works.
-D and -U options are processed in the order they are given on the command line. All -imacros file and -include file options are processed after all -D and -U options. Order matters, it's giving main character sequencing. π
-Hβ print the name of each header file used, in addition to other normal activities. Each name is indented to show how deep in the'#include'stack it is. It's the family tree of includes, fr fr. π³-Pβ inhibit generation of linemarkers in the output from the preprocessor. This might be useful when running the preprocessor on something that is not C code, and will be sent to a program which might be confused by the linemarkers. No linemarkers, no confusion, vibe check passed. π-Unameβ cancel any previous definition of name, either built in or provided with a-Doption. Yeet that macro.
π¨ Options to request or suppress errors and warnings π¨
Errors are diagnostic messages that report that the GNU Fortran compiler cannot compile the relevant piece of source code. The compiler will continue to process the program in an attempt to report further errors to aid in debugging, but will not produce any compiled output. It's like "okay we can't do it but let me tell you everything that's wrong first". π
Warnings are diagnostic messages that report constructions which are not inherently erroneous but which are risky or suggest there is likely to be a bug in the program. Unless -Werror is specified, they do not prevent compilation of the program. Warnings are the "girl, just so you knowβ¦" of diagnostics. π«Ά
You can request many specific warnings with options beginning -W, for example -Wimplicit to request warnings on implicit declarations. Each of these specific warning options also has a negative form beginning -Wno- to turn off warnings; for example, -Wno-implicit. This manual lists only one of the two forms, whichever is not the default. β¨
These options control the amount and kinds of errors and warnings produced by GNU Fortran:
-fmax-errors=nβ limits the maximum number of error messages to n, at which point GNU Fortran bails out rather than attempting to continue processing the source code. If n is0, there is no limit on the number of error messages produced. Zero means infinite chaos, iconic. π₯-fsyntax-onlyβ check the code for syntax errors, but do not actually compile it. This will generate module files for each module present in the code, but no other output file. Just a vibe check, no actual build. π-Wpedantic-pedanticβ issue warnings for uses of extensions to Fortran.-pedanticalso applies to C-language constructs where they occur in GNU Fortran source files, such as use of\ein a character constant within a directive like"#include".
Valid Fortran programs should compile properly with or without this option. However, without this option, certain GNU extensions and traditional Fortran features are supported as well. With this option, many of them are rejected.
Some users try to use -pedantic to check programs for conformance. They soon find that it does not do quite what they want---it finds some nonstandard practices, but not all. However, improvements to GNU Fortran in this area are welcome. (Not me volunteering to fix itβ¦ unless π)
This should be used in conjunction with -std=f95, -std=f2003, -std=f2008 or -std=f2018. Team effort, bestie. π
-pedantic-errorsβ like-pedantic, except that errors are produced rather than warnings. Same energy, turned all the way up. π₯-Wallβ enables commonly used warning options pertaining to usage that we recommend avoiding and that we believe are easy to avoid. This currently includes-Waliasing,-Wampersand,-Wconversion,-Wsurprising,-Wc-binding-type,-Wintrinsics-std,-Wtabs,-Wintrinsic-shadow,-Wline-truncation,-Wtarget-lifetime,-Winteger-division,-Wreal-q-constant,-Wunusedand-Wundefined-do-loop. The whole squad, assembled. π-Waliasingβ warn about possible aliasing of dummy arguments. Specifically, it warns if the same actual argument is associated with a dummy argument withINTENT(IN)and a dummy argument withINTENT(OUT)in a call with an explicit interface.
The following example will trigger the warning.
interface
subroutine bar(a,b)
integer, intent(in) :: a
integer, intent(out) :: b
end subroutine
end interface
integer :: a
call bar(a,a)
Yeah that call bar(a,a) is the crime scene. π¨
-Wampersandβ warn about missing ampersand in continued character constants. The warning is given with-Wampersand,-pedantic,-std=f95,-std=f2003,-std=f2008and-std=f2018. Note: with no ampersand given in a continued character constant, GNU Fortran assumes continuation at the first non-comment, non-whitespace character after the ampersand that initiated the continuation. It just guesses, and honestly same. π-Warray-temporariesβ warn about array temporaries generated by the compiler. The information generated by this warning is sometimes useful in optimization, in order to avoid such temporaries. Free optimization intel, we love to see it. π-Wc-binding-typeβ bestie this one warns you when a variable might not be C interoperable π¬ specifically if it got declared with an intrinsic type using the default kind instead of a kind parameter that's actually defined for C interoperability in the intrinsicISO_C_Bindingmodule. And psst,-Wallimplies this one. β¨-Wcharacter-truncationβ warns when a character assignment is gonna truncate the string you're assigning. the disrespect fr π-Wline-truncationβ warns when a source code line is about to get truncated.-Wallimplies it. And for free-form source code, the default is-Werror=line-truncation, so truncations get reported as errors β no soft launch for those, periodt.-Wconversionβ warns about implicit conversions that are likely to change the value of the expression after conversion. implied by-Wallπ-Wconversion-extraβ warns about implicit conversions between different types and kinds. ngl this one does not imply-Wconversion, they're separate girlies.-Wextraβ turns on some warning options for usages of language features that might be problematic. right now it includes-Wcompare-reals,-Wunused-parameterand-Wdo-subscript. it's giving "let me hold your hand through this" π«Ά-Wfrontend-loop-interchangeβ warns when you're using-ffrontend-loop-interchangeto do loop interchanges. heads up bestie π-Wimplicit-interfaceβ warns if a procedure gets called without an explicit interface. but lowkey read the fine print: this only checks that an explicit interface is present. it does not check that the declared interfaces are consistent across program units. so like, it's checking the vibe, not the receipts π-Wimplicit-procedureβ warns if a procedure is called that has neither an explicit interface nor has been declared asEXTERNAL.-Winteger-divisionβ warns if a constant integer division truncates its result. for example,3/5evaluates to0. yes, zero. the math is mathing but the vibe is not π-Wintrinsics-stdβ warns if gfortran finds a procedure named like an intrinsic that's not available in the currently selected standard (with-std) and treats it as anEXTERNALprocedure because of that. and-fall-intrinsicscan be used to never trigger this behavior and always link to the intrinsic regardless of the selected standard. iconic escape hatch β¨-Wno-overwrite-recursiveβ do not warn when-fno-automaticis used with-frecursive. > β οΈ real talk: recursion will be broken if the relevant local variables don't have theAUTOMATICattribute explicitly declared. this option can be used to suppress the warning when it is known that recursion is not broken. useful for build environments that use-Werror. π-Wreal-q-constantβ produces a warning if a real-literal-constant contains a"q"exponent-letter.-Wsurprisingβ produces a warning when"suspicious"code constructs are encountered. while technically legal, these usually indicate that an error has been made π
this currently produces a warning under the following circumstances:
- An
INTEGER SELECTconstruct has aCASEthat can never be matched as its lower value is greater than its upper value. - A
LOGICAL SELECTconstruct has threeCASEstatements. - A
TRANSFERspecifies a source that is shorter than the destination. - The type of a function result is declared more than once with the same type. If
-pedanticor standard-conforming mode is enabled, this is an error. - A
"CHARACTER"variable is declared with negative length.
-Wtabsβ by default, tabs are accepted as whitespace, but tabs are not members of the Fortran Character Set. for continuation lines, a tab followed by a digit between 1 and 9 is supported.-Wtabswill cause a warning to be issued if a tab is encountered. note:-Wtabsis active for-pedantic,-std=f95,-std=f2003,-std=f2008,-std=f2018and-Wall. π-Wundefined-do-loopβ warns if aDOloop with step either1or-1yields an underflow or an overflow during iteration of an induction variable of the loop. implied by-Wall.-Wunderflowβ produces a warning when numerical constant expressions are encountered which yield anUNDERFLOWduring compilation. enabled by default, so she's always on π-Wintrinsic-shadowβ warns if a user-defined procedure or module procedure has the same name as an intrinsic; in this case, an explicit interface or"EXTERNAL"or"INTRINSIC"declaration might be needed to get calls later resolved to the desired intrinsic/procedure. implied by-Wall. identity crisis core π-Wuse-without-onlyβ warns if a"USE"statement has no"ONLY"qualifier and thus implicitly imports all public entities of the used module. we love boundaries, bestie πΈ-Wunused-dummy-argumentβ warns about unused dummy arguments. implied by-Wall.-Wunused-parameterβ okay so contrary to gcc's meaning of-Wunused-parameter, gfortran's implementation of this option does not warn about unused dummy arguments (see-Wunused-dummy-argument), but about unused"PARAMETER"values. and-Wunused-parameteris implied by-Wextraif also-Wunusedor-Wallis used. different name, different job, iykyk β¨-Walign-commonsβ by default, gfortran warns about any occasion of variables being padded for proper alignment inside a"COMMON"block. this warning can be turned off via-Wno-align-commons. see also-falign-commons.-Wfunction-eliminationβ warns if any calls to impure functions are eliminated by the optimizations enabled by the-ffrontend-optimizeoption. implied by-Wextra. the way it just vanishes them π-Wrealloc-lhsβ warns when the compiler might insert code to for allocation or reallocation of an allocatable array variable of intrinsic type in intrinsic assignments. in hot loops, the Fortran 2003 reallocation feature may reduce the performance. if the array is already allocated with the correct shape, consider using a whole-array array-spec (e.g."(:,:,:)") for the variable on the left-hand side to prevent the reallocation check. note that in some cases the warning is shown, even if the compiler will optimize reallocation checks away. for instance, when the right-hand side contains the same variable multiplied by a scalar. see also-frealloc-lhs.-Wrealloc-lhs-allβ warns when the compiler inserts code to for allocation or reallocation of an allocatable variable; this includes scalars and derived types. she's thorough π-Wcompare-realsβ warns when comparing real or complex types for equality or inequality. implied by-Wextra.-Wtarget-lifetimeβ warns if the pointer in a pointer assignment might be longer than the its target. implied by-Wall. the age gap is real π-Wzerotripβ warns if a"DO"loop is known to execute zero times at compile time. implied by-Wall.-Wdo-subscriptβ warns if an array subscript inside a DO loop could lead to an out-of-bounds access even if the compiler cannot prove that the statement is actually executed, in cases like
real a(3)
do i=1,4
if (condition(i)) then
a(i) = 1.2
end if
end do
this option is implied by -Wextra. π
-Werrorβ turns all warnings into errors. no more gentle reminders, bestie, everything is a whole situation now π
some of these have no effect when compiling programs written in Fortran. fr fr, just so you know π
π Options for debugging your program or GNU Fortran π
GNU Fortran has various special options that are used for debugging either your program or the GNU Fortran compiler. detective mode: activated πβ¨
-fdump-fortran-originalβ outputs the internal parse tree after translating the source program into internal representation. this option is mostly useful for debugging the GNU Fortran compiler itself. the output generated by this option might change between releases. > this option may also generate internal compiler errors for features which have only recently been added. π-fdump-fortran-optimizedβ outputs the parse tree after front-end optimization. mostly useful for debugging the GNU Fortran compiler itself. the output generated by this option might change between releases. > this option may also generate internal compiler errors for features which have only recently been added. π¬-fdump-parse-treeβ outputs the internal parse tree after translating the source program into internal representation. mostly useful for debugging the GNU Fortran compiler itself. the output generated by this option might change between releases. this option may also generate internal compiler errors for features which have only recently been added. > this option is deprecated; use-fdump-fortran-originalinstead. don't use the old one bestie, she's retired π-fdebug-aux-varsβ renames internal variables created by the gfortran front end and makes them accessible to a debugger. the name of the internal variables then start with upper-case letters followed by an underscore. this option is useful for debugging the compiler's code generation together with-fdump-tree-originaland enabling debugging of the executable program by using-gor-ggdb3. β¨-fdump-fortran-globalβ outputs a list of the global identifiers after translating into middle-end representation. mostly useful for debugging the GNU Fortran compiler itself. the output generated by this option might change between releases. > this option may also generate internal compiler errors for features which have only recently been added. π«-ffpe-trap=listβ specify a list of floating point exception traps to enable. on most systems, if a floating point exception occurs and the trap for that exception is enabled, aSIGFPEsignal will be sent and the program being aborted, producing a core file useful for debugging. list is a (possibly empty) comma-separated list of the following exceptions:invalid(invalid floating point operation, such asSQRT(-1.0)),zero(division by zero),overflow(overflow in a floating point operation),underflow(underflow in a floating point operation),inexact(loss of precision during operation), anddenormal(operation performed on a denormal value). the first five exceptions correspond to the five IEEE 754 exceptions, whereas the last one (denormal) is not part of the IEEE 754 standard but is available on some common architectures such as x86. π§
the first three exceptions (invalid, zero, and overflow) often indicate serious errors, and unless the program has provisions for dealing with these exceptions, enabling traps for these three exceptions is probably a good idea. > like, genuinely, turn these on, bestie π«Ά
if the option is used more than once in the command line, the lists will be joined: "ffpe-trap="list1 "ffpe-trap="list2 is equivalent to "ffpe-trap="list1,list2.
Note that once an exception trap is turned on, it can't be turned back off β there's literally no negative form. No take-backsies. π
And okay, real talk: so many floating point operations lose precision from rounding that -ffpe-trap=inexact is gonna be kinda uninteresting in actual practice. Like, it'll fire constantly and you'll be like "bestie why." π
By default, no exception traps are enabled. Chill vibes only.
-ffpe-summary=listβ give it a list of floating-point exceptions whose flag status gets printed toERROR_UNITwhenever you invokeSTOPorERROR STOP. list can benone,all, or a comma-separated list of these little guys:invalid,zero,overflow,underflow,inexact, anddenormal. (Peep-ffpe-trapif you want the tea on what each exception actually means.) If you use this option more than once on the command line, only the last one counts, periodt. And by default? You get a summary of all the exceptions exceptinexact. π-fno-backtraceβ so when something truly catastrophic happens at runtime, or a deadly signal gets emitted (segmentation fault,illegal instruction,bus error,floating-point exception, and all the other POSIX signals that have the action core), the Fortran runtime library tries to print you a backtrace of the error.-fno-backtracekills that backtrace generation. β°οΈ Heads up though: this option only has any influence when you're compiling the Fortran main program.
β¨ Options for directory search β¨
These ones control how GNU Fortran hunts down files named by the INCLUDE directive, and where it goes looking for previously compiled modules. π
It also messes with the search paths that cpp uses when it's preprocessing Fortran source.
-Idirβ these affect how theINCLUDEdirective gets interpreted (and also the#includedirective of the cpp preprocessor). Also note that the general behavior of-IandINCLUDEis pretty much the same as-Iwith#includein the cpp preprocessor, as far as looking forheader.gccfiles and other such things goes. This path is also used to search for.modfiles when aUSEstatement needs previously compiled modules. π-Jdirβ tells the compiler where to put.modfiles for compiled modules. It also gets added to the list of directories that aUSEstatement searches. The default is the current directory. π-fintrinsic-modules-pathdir β points at the location of pre-compiled intrinsic modules, for when they're not sitting in the default location the compiler expects. π§
π Influencing the linking step π
These options only come into play when the compiler is linking object files into an executable output file. If the compiler isn't doing a link step, they're meaningless. π
-static-libgfortranβ on systems that providelibgfortranas both a shared and a static library, this forces the static version to be used. If no shared version oflibgfortranwas even built when the compiler was configured, then this option does absolutely nothing. π€·ββοΈ
π¬ Influencing runtime behavior π¬
These ones change the runtime behavior of programs compiled with GNU Fortran. Big main character energy.
-fconvert=conversionβ specifies the representation of data for unformatted files. Valid values for conversion on most systems are:native(the default),swap(swap between big- and little-endian),big-endian(use big-endian representation for unformatted files), andlittle-endian(use little-endian representation for unformatted files).
On POWER systems that support -mabi=ieeelongdouble, there are extra options, and you can combine them with the others using commas. Those are:
-fconvert=r16_ieeeβ use IEEE 128-bit format forREAL(KIND=16).-fconvert=r16_ibmβ use IBM long double format forREAL(KIND=16).
This option only has an effect when it's used in the main program. TheCONVERTspecifier and theGFORTRAN_CONVERT_UNITenvironment variable both override the default that-fconvertsets. π
-frecord-marker=lengthβ sets the length of record markers for unformatted files. Valid values for length are4and8. Default is4. Fun fact: this is different from previous versions of gfortran, which defaulted to a record marker length of8on most systems. So if you wanna read or write files that are compatible with earlier gfortran versions, use-frecord-marker=8. π°οΈ-fmax-subrecord-length=lengthβ sets the maximum length for a subrecord. The max permitted value for length is2147483639, which is also the default. Honestly? Only really useful for the gfortran testsuite. π-fsign-zeroβ when enabled, floating point numbers of value zero with the sign bit set get written as a negative number in formatted output, and get treated as negative in theSIGNintrinsic.-fno-sign-zerodoes not print the negative sign of zero values (or values rounded to zero for I/O) and regards zero as a positive number in theSIGNintrinsic, for compatibility with Fortran 77. The default is-fsign-zero. β
π Options for code generation conventions π
These machine-independent options control the interface conventions used in code generation. Very behind-the-scenes, very iykyk.
Most of them have both a positive and a negative form β the negative form of -ffoo would be -fno-foo. In the table below, only one of the forms is listed, and it's the one that isn't the default. You can figure out the other form by either removing the no- or adding it. Easy. β¨
-fno-automaticβ treat each program unit (except the ones marked asRECURSIVE) as if theSAVEstatement were specified for every local variable and array referenced inside it. Does not affect common blocks. (Some Fortran compilers offer this same option under the name-staticor-save.) The default, which is-fautomatic, uses the stack for local variables smaller than the value given by-fmax-stack-var-size. If you want no static memory at all, use the option-frecursive. Local variables or arrays that have an explicitSAVEattribute get silently ignored unless you also add the-pedanticoption. π€«-ff2cβ generate code designed to be compatible with code generated byg77andf2c. The calling conventions used byg77(originally implemented inf2c) require functions that return type defaultREALto actually return the C typedouble, and functions that return typeCOMPLEXto return their values via an extra argument in the calling sequence that points to where the return value should be stored. Under the default GNU calling conventions, such functions just return their results the way they would in GNU C β defaultREALfunctions return the C typefloat, andCOMPLEXfunctions return the GNU C typecomplex. On top of that, this option implies the-fsecond-underscoreoption, unless-fno-second-underscoreis explicitly requested.
This does not affect the generation of code that interfaces with the libgfortran library.
Caution: it is not a good idea to mix Fortran code compiled with-ff2cwith code compiled using the default-fno-f2ccalling conventions, because callingCOMPLEXor defaultREALfunctions between program parts that were compiled with different calling conventions will break at execution time. π
Caution: this will also break code that passes intrinsic functions of type defaultREALorCOMPLEXas actual arguments, because the library implementations use the-fno-f2ccalling conventions. π
-fno-underscoringβ don't transform the names of entities specified in the Fortran source file by appending underscores to them. With-funderscoringin effect, GNU Fortran appends one underscore to external names that have no underscores. This is done to keep things compatible with code produced by many UNIX Fortran compilers. πΈ
Caution: the default behavior of GNU Fortran is incompatible withf2candg77. Please use the-ff2coption if you want object files compiled with GNU Fortran to be compatible with object code created by those tools. π
Using -fno-underscoring is not recommended unless you're out here experimenting with stuff like integrating GNU Fortran into existing system environments (vis-Γ -vis existing libraries, tools, and so on).
For example, with -funderscoring, and assuming that j() and max_count() are external functions while my_var and lvar are local variables, a statement like
I = J() + MAX_COUNT (MY_VAR, LVAR)
gets implemented as something akin to:
i = j_() + max_count__(&my_var__, &lvar);
With -fno-underscoring, that same statement is implemented as:
i = j() + max_count(&my_var, &lvar);
Using -fno-underscoring lets you directly specify user-defined names while debugging and when interfacing GNU Fortran code with other languages. π
But note that just because the names match doesn't mean the interface GNU Fortran implements for an external name matches the interface some other language implements for that same name. Like, getting code produced by GNU Fortran to link to code produced by some other compiler using this or any other method can be only a small part of the overall solution β getting the code generated by both compilers to agree on issues other than naming can require significant effort, and unlike naming disagreements, linkers normally cannot detect disagreements in these other areas. π
Also, note that with -fno-underscoring, the lack of appended underscores introduces the very real possibility that a user-defined external name will conflict with a name in a system library, which could make finding unresolved-reference bugs quite difficult in some cases β they might occur at program run time and show up only as buggy behavior at run time. π
In future versions of GNU Fortran we hope to improve naming and linking issues so that debugging always involves using the names as they appear in the source, even if the names as seen by the linker are mangled to prevent accidental linking between procedures with incompatible interfaces. π¦
-fsecond-underscoreβ by default, GNU Fortran appends an underscore to external names. If this option is used, GNU Fortran appends two underscores to names with underscores and one underscore to external names with no underscores. GNU Fortran also appends two underscores to internal names with underscores to avoid naming collisions with external names. This option has no effect if-fno-underscoringis in effect. It is implied by the-ff2coption. β¨
Otherwise, with this option, an external name like MAX_COUNT gets implemented as a reference to the link-time external symbol max_count__, instead of max_count_. Why the double underscore tho? Because that's what g77 and f2c expect, bestie β it's required for compatibility with them, and it's implied by using the -ff2c option. β¨
-fcoarray=<keyword>β coarrays, but make it a choice. Pick your fighter:noneβ turn coarray support all the way off. Use a coarray declaration or an image-control statement and boom π compile-time error. (This is the default.)singleβ single-image mode, meaningnum_images()is literally always one. One image, one vibe.libβ library-based coarray parallelization; you're gonna need to link a suitable GNU Fortran coarray library. No library, no party. π
-fcheck=<keyword>β turns on generation of run-time checks! The argument has to be a comma-delimited list of these keywords, and if you slap ano-in front of a check, it disables that check if a previous specification had turned it on. Takebacks are allowed. πallβ enable all run-time tests of-fcheck. The whole menu.array-tempsβ warns at run time when a temporary array had to be generated for passing an actual argument. That info is sometimes genuinely useful for optimization, so you can dodge those temporaries.- Note: this warning only prints once per location.
bitsβ enable generation of run-time checks for invalid arguments to the bit manipulation intrinsics. Bits stay valid or we riot.boundsβ enable generation of run-time checks for array subscripts and against the declared minimum and maximum values. It also checks array indices for assumed and deferred shape arrays against the actual allocated bounds, and makes sure all string lengths are equal for character array constructors without an explicit typespec.- Some of these checks require that
-fcheck=boundsis set for the compilation of the main program too. - Note: in the future this may also include other forms of checking, e.g., checking substring references. π
- Some of these checks require that
doβ enable generation of run-time checks for invalid modification of loop iteration variables. Don't touch the loop variable, I'm begging πmemβ enable generation of run-time checks for memory allocation.- Note: this option does not affect explicit allocations using the
ALLOCATEstatement β those are always checked. Always. Periodt.
- Note: this option does not affect explicit allocations using the
pointerβ enable generation of run-time checks for pointers and allocatables.recursionβ enable generation of run-time checks for recursively called subroutines and functions that are not marked as recursive. See also-frecursive.- Note: this check does not work for OpenMP programs and is disabled if used together with
-frecursiveand-fopenmp.
- Note: this check does not work for OpenMP programs and is disabled if used together with
Example: say you have a file foo.f90, then this command
gfortran -fcheck=all,no-array-temps foo.f90
will compile the file with all the checks enabled as specified above, except the warnings for generated array temporaries. All the drama, minus one specific thing. π¦
-fbounds-checkβ deprecated alias for-fcheck=bounds. Old name, still works, but like... use the new one.-ftail-call-workaround-ftail-call-workaround=nβ okay so some C interfaces to Fortran codes violate the gfortran ABI by omitting the hidden character length arguments as described in. This can lead to crashes because pushing arguments for tail calls can overflow the stack. Not cute, not slay, just danger.- To provide a workaround for existing binary packages, this option disables tail call optimization for gfortran procedures with character arguments.
- With
-ftail-call-workaround=2, tail call optimization is disabled in all gfortran procedures with character arguments. - With
-ftail-call-workaround=1(or the equivalent plain-ftail-call-workaround), it's disabled only in gfortran procedures with character arguments that call implicitly prototyped procedures. - Using this option can lead to problems including crashes due to insufficient stack space. Yeah, the workaround has its own issues, bestie.
- It is very strongly recommended to fix the code in question. The
-fc-prototypes-externaloption can be used to generate prototypes which conform to gfortran's ABI, for inclusion in the source code. That's the actual fix. π«Ά - Support for this option will likely be withdrawn in a future release of gfortran. It's giving temporary.
- The negative form,
-fno-tail-call-workaround, or the equivalent-ftail-call-workaround=0, can be used to disable this option. - Default is currently
-ftail-call-workaroundβ but that will change in future releases. β οΈ
-fcheck-array-temporariesβ deprecated alias for-fcheck=array-temps.-fmax-array-constructor=nβ use this to raise the upper limit permitted in array constructors. The code below literally requires this option to expand the array at compile time:
program test
implicit none
integer j
integer, parameter :: n = 100000
integer, parameter :: i(n) = (/ (2*j, j = 1, n) /)
print '(10(I0,1X))', i
end program test
Caution: this option can lead to long compile times and excessively large object files. Your compiler is gonna be in the group chat for a WHILE. π
The default value for n is 65535.
-fmax-stack-var-size=nβ this one specifies the size in bytes of the largest array that will be put on the stack. If the size is exceeded, static memory is used instead (except in procedures marked asRECURSIVE). Use-frecursiveto allow for recursive procedures which don't have aRECURSIVEattribute, or for parallel programs. Use-fno-automaticto never use the stack at all.- Currently this option only affects local arrays declared with constant bounds, and it may not apply to all character variables. Future versions of GNU Fortran may improve this behavior. It's a work in progress, and that's okay. πΈ
- The default value for n is
65536.
-fstack-arraysβ adding this makes the Fortran compiler put all arrays of unknown size and array temporaries onto stack memory. If your program uses very large local arrays, you may have to extend your runtime limits for stack memory on some operating systems. Lowkey a vibe check for your stack. π§- This flag is enabled by default at optimization level
-Ofastunless-fmax-stack-var-sizeis specified.
- This flag is enabled by default at optimization level
-fpack-derivedβ tells GNU Fortran to pack derived type members as closely as possible. But heads up: code compiled with this option is likely to be incompatible with code compiled without it, and it may execute slower. Choose wisely. π-frepack-arraysβ in some circumstances GNU Fortran may pass assumed shape array sections via a descriptor describing a noncontiguous area of memory. This option adds code to the function prologue to repack that data into a contiguous block at runtime.- This should result in faster accesses to the array. However, it can introduce significant overhead to the function call, especially when the passed data is noncontiguous. Trade-offs, bestie, it's always trade-offs.
-fshort-enumsβ provided for interoperability with C code that was compiled with the-fshort-enumsoption. It makes GNU Fortran choose the smallestINTEGERkind a given enumerator set will fit in, and gives all its enumerators that kind. Small and efficient, we love her. π-finline-arg-packingβ when passing an assumed-shape argument of a procedure as an actual argument to an assumed-size or explicit size procedure, or as an argument to a procedure that doesn't have an explicit interface, the argument may have to be packed β that is, put into contiguous memory. An example is the call tofooin:
subroutine foo(a)
real, dimension(*) :: a
end subroutine foo
subroutine bar(b)
real, dimension(:) :: b
call foo(b)
end subroutine bar
When -finline-arg-packing is in effect, this packing will be performed by inline code. This allows for more optimization while increasing code size. Bigger code, better optimization, the eternal deal. β¨
-finline-arg-packingis implied by any of the-Ooptions, except when optimizing for size via-Os. If the code contains a very large number of arguments that have to be packed, code size and also compilation time may become excessive. If that's the case, it may be better to disable this option. You can find instances of packing by using-Warray-temporaries.
-fexternal-blasβ this makes gfortran generate calls to BLAS functions for some matrix operations likeMATMUL, instead of using our own algorithms, if the size of the matrices involved is larger than a given limit (see-fblas-matmul-limit). This may be profitable if an optimized vendor BLAS library is available. The BLAS library will have to be specified at link time. π₯-fblas-matmul-limit=nβ only significant when-fexternal-blasis in effect. Matrix multiplication of matrices with size larger than (or equal to) n will be performed by calls to BLAS functions, while others will be handled by gfortran internal algorithms. If the matrices involved aren't square, the size comparison is performed using the geometric mean of the dimensions of the argument and result matrices. Math girlies, we see you. π- The default value for n is
30.
- The default value for n is
-finline-matmul-limit=nβ when front-end optimization is active, some calls to theMATMULintrinsic function will be inlined. This may result in a code size increase if the size of the matrix can't be determined at compile time, since code for both cases gets generated.- Setting
-finline-matmul-limit=0will disable inlining in all cases. - Setting this option with a value of n will produce inline code for matrices with size up to n. If the matrices involved aren't square, the size comparison is performed using the geometric mean of the dimensions of the argument and result matrices.
- The default value for n is
30. The-fblas-matmul-limitcan be used to change this value.
- Setting
-frecursiveβ allows indirect recursion by forcing all local arrays to be allocated on the stack. π«Ά- This flag cannot be used together with
-fmax-stack-var-size=or-fno-automatic. It's a hard no, not a soft no. Do not.
- This flag cannot be used together with
-finit-local-zero,-finit-derived,-finit-integer=n,-finit-real=<zero|inf|-inf|nan|snan>,-finit-logical=<true|false>,-finit-character=nβ okay bestie, this whole squad is about initializing your local variables so they don't show up to the party as mystery garbage. β¨
So -finit-local-zero tells the compiler: local INTEGER, REAL, and COMPLEX variables β zero; LOGICAL variables β false; CHARACTER variables β a string of null bytes. Periodt.
But if you want finer control, there's a whole set of tiny levers: -finit-integer=n, -finit-real=<zero|inf|-inf|nan|snan> (and yes this one also initializes the real AND imaginary parts of your local COMPLEX variables, because complex is just two reals in a trench coat π
), -finit-logical=<true|false>, and -finit-character=n β where n is an ASCII character value. Slay.
Then -finit-derived steps in for your derived type girlies: with it, components of derived type variables get initialized according to all those flags above. And any component whose type isn't covered by an explicit -finit-* flag? It gets treated exactly like -finit-local-zero would treat it. πΈ
BUT. These options do not initialize: - objects with thePOINTERattribute - allocatable arrays - variables that appear in anEQUIVALENCEstatement. (and the manpage says these limitations may be removed in future releases β so like, watch this space π)
Also important, not me letting you miss this: -finit-real=nan initializes REAL and COMPLEX variables with a quiet NaN. Want a signalling NaN instead? Use -finit-real=snan. BUT β and this is the tea β compile-time optimizations may convert them into quiet NaN anyway, and trapping needs to be enabled (e.g. via -ffpe-trap). So it's giving "I tried" energy sometimes. π
Oh and -finit-integer β it parses your value into an integer of type INTEGER(kind=C_LONG) on the host. Then that value gets assigned to the integer variables in the Fortran code, which might result in wraparound if the value is too large for the kind. So don't go feral with big numbers, bestie.
Finally: enabling ANY of the -finit-* options will silence warnings that -Wuninitialized would've emitted for the affected local variables. So you're trading warnings for defaults. Just so you know. π«Ά
-falign-commonsβ by default,gfortranenforces proper alignment of all variables in aCOMMONblock by padding them as needed. On certain platforms this is mandatory, on others it just increases performance. But here's the catch: if aCOMMONblock isn't declared with consistent data types everywhere, that padding can cause trouble, and-fno-align-commonscan be used to disable automatic alignment. π
The same form of this option should be used for ALL files that share a COMMON block β consistency is the vibe check. And to avoid potential alignment issues in COMMON blocks, it's recommended to order objects from largest to smallest. Iconic organizational tip, honestly.
-fno-protect-parensβ by default, the parentheses in expressions are honored for all optimization levels, such that the compiler does NOT do any re-association. Like, your parentheses are sacred. π
Using -fno-protect-parens lets the compiler reorder REAL and COMPLEX expressions to produce faster code. But heads up: for the re-association optimization, -fno-signed-zeros AND -fno-trapping-math need to be in effect. The parentheses protection is enabled by default β unless -Ofast is given. π
-frealloc-lhsβ an allocatable left-hand side of an intrinsic assignment gets automatically (re)allocated if it's either unallocated or has a different shape. This option is enabled by default, EXCEPT when-std=f95is given. See also-Wrealloc-lhs. β¨-faggressive-function-eliminationβ functions with identical argument lists are eliminated within statements, regardless of whether these functions are markedPUREor not. For example, in:
a = f(b,c) + f(b,c)
there will only be a single call to f. Efficient queen behavior. π₯ But note: this option only works if -ffrontend-optimize is in effect.
-ffrontend-optimizeβ this one performs front-end optimization, based on manipulating parts the Fortran parse tree. It's enabled by default by any-Ooption EXCEPT-O0and-Og. The optimizations enabled by this option include:- inlining calls to
MATMUL - elimination of identical function calls within expressions
- removing unnecessary calls to
TRIMin comparisons and assignments - replacing
TRIM(a)witha(1:LEN_TRIM(a))and - short-circuiting of logical operators (
.AND.and.OR.).
- inlining calls to
It can be deselected by specifying -fno-frontend-optimize. π¦
-ffrontend-loop-interchangeβ attempts to interchange loops in the Fortran front end where profitable. Enabled by default by any-Ooption. At the moment, this option only affectsFORALLandDO CONCURRENTstatements with several forall triplets. Niche but it ate. π
β¨ ENVIRONMENT β¨
Okay so, the tea: the gfortran compiler currently does not make use of any environment variables to control its operation above and beyond those that affect the operation of gcc. So like, it's not hiding secret env vars from you. It's just gcc's env vars doing gcc's thing. Periodt. π
π BUGS π
Found a bug? First of all, relatable. For instructions on reporting bugs, see:
<file:///usr/share/doc/gcc-12/README.Bugs>
Go tell them bestie, they wanna know. π«Ά
π SEE ALSO π
The whole friend group, assembled: gpl(7), gfdl(7), fsf-funding(7), cpp(1), gcov(1), gcc(1), as(1), ld(1), gdb(1), dbx(1) β and the Info entries for gcc, cpp, gfortran, as, ld, binutils and gdb. π
π AUTHOR π
See the Info entry for gfortran for contributors to GCC and GNU Fortran. Shoutout to the contributors, absolute legends. π
π COPYRIGHT π
Copyright (c) 2004-2022 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being "Funding Free Software", the Front-Cover Texts being (a) (see below), and with the Back-Cover Texts being (b) (see below). A copy of the license is included in the gfdl(7) man page. π
(a) The FSF's Front-Cover Text is:
A GNU Manual
(b) The FSF's Back-Cover Text is:
You have freedom to copy and modify this GNU Manual, like GNU
software. Copies published by the Free Software Foundation raise
funds for GNU development.
and that's a wrap on the whole page, bestie!! π this wasgcc-12, dated2024-07-11, from theGFORTRAN(1)manual. go forth and compile something iconic. no cap. πβ¨
π¦ where this page comes from
- ubuntu noble: gfortran-12-mips-linux-gnu 12.4.0-2ubuntu1~24.04cross8
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms