我最近正在开发一个相当长的 Fortran 代码。我使用的编译器是 Opensuse 13.1(64 位)上的 gfortran 4.8.1。但是,当我使用 -O2 或 -O3 选项编译代码时,我收到了许多关于“-Wmaybe-uninitialized”的警告。我设法将代码减少到最小的工作示例,如下所示。

在 main.f90

program main
    use modTest
    implicit none

    real(kind = 8), dimension(:, :), allocatable :: output
    real(kind = 8), dimension(:, :, :), allocatable :: input

    allocate(input(22, 33, 20), output(22, 33))
    input = 2.0
    call test(input, output)

end program main

在 test.f90
module modTest
contains
subroutine test(inputValue, outValue)
    use modGlobal
    implicit none

    real(kind = 8), dimension(:, :, :), intent(in) :: inputValue
    real(kind = 8), dimension(:, :), intent(out) :: outValue
    integer :: nR, nX, nM, iM, ALLOCATESTATUS
    real, dimension(:, :, :), allocatable :: cosMPhi

    nR = size(inputValue, 1)
    nX = size(inputValue, 2)
    nM = size(inputValue, 3) - 1
    allocate(cosMPhi(nR, nX, 0:nM), stat=ALLOCATESTATUS)
    call checkStatus(ALLOCATESTATUS)
    do iM = 0, nM
        cosMPhi(:, :, iM) = cos(iM * 1.0)
    end do
    outValue =  sum(inputValue * cosMPhi, 3)

end subroutine
end module

在 global.f90
module modGlobal
contains
    subroutine checkStatus(stat)
        implicit none
        integer, intent(in) :: stat
        if(stat /= 0) then
           print *, "allocation failed"
           stop
        end if
   end subroutine
end module

使用 gfortran -O2 -Wall test.f90 main.f90 -o run 编译时,会出现以下警告:
test.f90: In function 'test':
test.f90:9:0: warning: 'cosmphi.dim[2].stride' may be used uninitialized in this function [-Wmaybe-uninitialized]
     real, dimension(:, :, :), allocatable :: cosMPhi
^
test.f90:9:0: warning: 'cosmphi.dim[1].ubound' may be used uninitialized in this function [-Wmaybe-uninitialized]
test.f90:9:0: warning: 'cosmphi.dim[1].stride' may be used uninitialized in this function [-Wmaybe-uninitialized]
test.f90:9:0: warning: 'cosmphi.dim[0].ubound' may be used uninitialized in this function [-Wmaybe-uninitialized]
test.f90:9:0: warning: 'cosmphi.offset' may be used uninitialized in this function [-Wmaybe-uninitialized]

虽然我试图用谷歌搜索这个问题一段时间,但我仍然没有找到一个好的答案。一些相关的网站是:
(1) https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58410
(2) https://groups.google.com/forum/m/#!topic/comp.lang.fortran/RRYoulcSR1k
(3) GCC -Wuninitialized / -Wmaybe-uninitialized issues

我使用 gfortran 4.8.5 测试了示例代码,但警告仍然存在。是不是因为我在代码中做错了什么?任何帮助将不胜感激。提前致谢!

最佳答案

这是因为您在 stat=ALLOCATESTATUS 的分配中使用了 cosMphi 但之后不检查状态变量的值。只是省略。然后,如果分配失败,程序就会崩溃——这是最简单的方法,除非您需要更强大/更复杂的响应。

关于linux - Gfortran 警告提示 "Wmaybe-uninitialized",我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34233374/

10-10 18:19