What flags to set for GFORTRAN compiler to catch faulty code?

I think I won't find that in any textbook, because answering this takes experience. I am currently in the stage of testing/validating my code / hunting bugs to get it into production state and any errors would lead to many people suffering e.g. the dark side.

  • What kind of flags can you set when you compile a program for Fortran for debugging purposes?

  • What kind of flags can you set for the production system?

  • What can you set before you deploy?


  • Bare minimum


    -O0 basically tells the compiler to make no optimisations. Optimiser can remove some local variables, merge some code blocks, etc. and as an outcome it can make debugging unpredictable. The price for -O0 option is very slow code execution, but starting from version 4.8 GCC compilers (including the Fortran one) accept a newly introduced optimisation level -Og:


    Optimize debugging experience. -Og enables optimizations that do not interfere with debugging. It should be the optimization level of choice for the standard edit-compile-debug cycle, offering a reasonable level of optimization while maintaining fast compilation and a good debugging experience.

    So, if possible use -Og, otherwise use -O0.


    This option actually makes debugging possible by requesting the compiler to produce debugging information intended to be used by interactive debugger (GDB).


    There are a plenty of them. The most useful in my opinion are:

    -Wall to "enable all the warnings about constructions that some users consider questionable, and that are easy to avoid (or modify to prevent the warning), even in conjunction with macros."

    -Wextra to "enable some extra warning flags that are not enabled by -Wall."

    -pedantic to generate warnings about language features that are supported by gfortran but are not part of the official Fortran 95 standard. It possible to be even more "pedantic" and use -std=f95 flag for warnings to become errors.

    -fimplicit-none to "specify that no implicit typing is allowed, unless overridden by explicit IMPLICIT statements. This is the equivalent of adding implicit none to the start of every procedure."

    -fcheck=all to "enable run-time tests", such as, for instance, array bounds checks.

    -fbacktrace to "specify that, when a runtime error is encountered or a deadly signal is emitted (segmentation fault, illegal instruction, bus error or floating-point exception), the Fortran runtime library should output a backtrace of the error."