Fortran undefined and unused variable warnings

Like other coding languages, Fortran code might have variables that are used before they are defined, or variables that are defined but never used. Uninitialized variables cause unexpected behavior that can be difficult to debug. Variables that are defined but never used are a waste of memory and possibly computation time and make the code less readable. Here is a trivial example of a Fortran program that has an undefined variable, that Fortran compilers generally don’t warn about by default, and may not even be able to warn at compile time.

program test
implicit none
integer :: i, j

i = j + 1
print '(i0)', i

end program test

We provide over 20 such tests in a CMake project that outputs JSON for the compiler tested.

GCC Gfortran 17 new compile-time warnings

GCC / GFortran 17 adds two Fortran compiler options to provide more robust (less false positive and false negative) warnings about undefined and unused variables. This is a potentially significant improvement over the -Wuninitialized and -Wmaybe-uninitialized flags, which operate on the Static Single Assignment (SSA) form and are known to be more likely to produce false positives and false negatives.

These new options are

The new -Wundefined-vars option by Thomas Koenig is in effect a front-end static analysis tool using tables of variable definitions and uses to determine if a variable is used before it is defined.

LLVM Flang Fortran compiler

The LLVM Flang compiler has an option -Wused-undefined-variable that at least in Flang 22.1 didn’t catch the undefined variable in the toy example above, but does catch the unused variable with the option -pedantic. It is mentioned in the Flang forums that the Flang team considers some of the cases Gfortran 17 catches to be for possibly future implemented runtime checks rather than compile-time checks as in GCC 17.

warning: Value of uninitialized local variable ‘i’ is used but never defined [-Wused-undefined-variable]

Intel oneAPI Fortran compiler

Uninitialized variable warnings are a runtime -check:uninit with “ifx” Fortran compiler, not currently available in compile-time -warn.

NVIDIA HPC SDK Fortran compiler

The “nvfortran” compiler nvfortran -help didn’t reveal any options to detect undefined variables beyond the usual -Mdclchk that enforces implicit none - but that’s a declaration check, not a defined variable check.