How to avoid global variables in Fortran 90 or higher?

有些话、适合烂在心里 提交于 2019-12-24 15:48:38

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/19040118/how-to-avoid-global-variables-in-fortran-90-or-higher

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!