在 Fortran 中使用全局变量时的错误结果 [英] Wrong result when using a global variable in Fortran
问题描述
我正在学习 Fortran 的基础知识.我创建了一个初始化矩阵的简单子程序:
I'm learning the basics of Fortran. I created a simple subroutine initializing a matrix:
program test
integer, parameter :: n = 1024
real :: a(n, n)
call init(a)
write (*, *) a(1, 1)
end program
subroutine init(a)
real :: a(n, n)
a(:, :) = 3.0
end subroutine
那么输出是 0.0
而不是预期的 3.0
.除此之外,valgrind
说:
Then the output is 0.0
instead of expected 3.0
. Apart from that, valgrind
says that:
==7006== Conditional jump or move depends on uninitialised value(s)
==7006== at 0x400754: init_ (in /home/marcin/proj/mimuw/fortran/test)
==7006== by 0x4007A4: MAIN__ (in /home/marcin/proj/mimuw/fortran/test)
==7006== by 0x40083B: main (in /home/marcin/proj/mimuw/fortran/test)
为什么?n
参数被编译器正确识别,应该是全局的.
Why? The n
parameter is correctly recognized by the compiler and should be a global one.
我用 gfortran 6.3.1 编译了程序
I compiled the program with gfortran 6.3.1
推荐答案
n
不是全局变量,是主程序的局部变量.
n
is not a global variable, it is a local variable of the main program.
子程序是一个完全独立于主程序的编译单元,它们不共享任何信息.
The subroutine is a completely independent compilation unit from the main program and they do not share any information.
一个子程序可以看到"父模块的其他变量,如果它是一个模块过程,或者是一个父(宿主)过程或程序的变量,如果它是一个内部过程.
A subroutine can "see" other variables of the parent module, if it is a module procedure, or variables of a parent (host) procedure or program if it is an internal procedure.
请务必阅读 Fortran 程序的结构并尽可能多地使用模块.更喜欢模块而不是内部过程.您将在链接中看到如何将子例程放入模块或如何将其置于主程序的内部.
Be sure to read about the structure of Fortran programs and use modules as much as possible. Prefer modules over internal procedures. You will see how to put the subroutine into a module or how to make it internal to the main program in the link.
我没有提到常见的块,只是不要使用它们,它们已经过时了.并且记住在每个编译单元中使用 implicit none
.
I did not mention common blocks, just don't use them, they are obsolete. And rember to use implicit none
in every compilation unit.
这篇关于在 Fortran 中使用全局变量时的错误结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!