如何避免Fortran 90或更高版本中的全局变量? [英] How to avoid global variables in Fortran 90 or higher?
问题描述
我有一个Fortran库,我必须通过一个非常特定的格式来传递函数。然后图书馆正在对我的功能进行一些操作。这个函数是由用户编写的(像我一样),并且该库是理所当然的。
不幸的是,为了计算我的函数,我需要一些值(其中一些值可以被初始化一劳永逸),我想避免使用 common
或 save
。
我读过我可以使用单例模式,但我对模板并不熟练,而且有些人批评它的用法。所以,
如何在函数内部传递我的变量,即使我不能在函数的参数中包含变量?
如果你定义了一个Fortran MODULE
,你可以让你的函数使用一些未在主程序中定义的变量:
MODULE mymod
REAL :: x = 1.35
INTEGER :: y = 16
CONTAINS
FUNCTION结果( a,b)
REAL :: a,结果
INTEGER :: b
结果= a * x +实数(b + y)
END FUNCTION结果
END MODULE mymod
程序extrn_func
USE mymod,ONLY:结果
PRINT *,结果(1.0,3)
结束程序extrn_func
虽然此方法要求您可以添加 USE mymod
声明到主程序。
I have a fortran library to which I must pass a function with a very specific format. The library then is doing some operation on my function. The function is written by a user (like me) and the library is given for granted.
Unfortunately to compute my function I need some values (some of them could be initialized once and for all in the main) and I would like to avoid the use of common
or save
.
I read I could use a singleton pattern but I am not very expert in template and on top of that some people criticize its use. So, how can I pass my variable inside the function even if I cannot have it in the arguments of my function?
If you define a Fortran MODULE
, you can have your function use some variables not defined in the main program:
MODULE mymod
REAL :: x = 1.35
INTEGER :: y = 16
CONTAINS
FUNCTION results(a,b)
REAL :: a, results
INTEGER :: b
results = a*x+real(b+y)
END FUNCTION results
END MODULE mymod
PROGRAM extrn_func
USE mymod, ONLY: results
PRINT *,results(1.0, 3)
END PROGRAM extrn_func
Though, this method requires you to be able to add the USE mymod
statement to the main program.
这篇关于如何避免Fortran 90或更高版本中的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!