如何在fortran模块中访问私有变量? [英] How to access private variables in fortran modules?

查看:54
本文介绍了如何在fortran模块中访问私有变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道私有变量的想法是不应访问它们,我确实希望在程序其余部分使用模块时以这种方式工作,但是我需要使用它来检查内部变量模块的工作原理.

I know the idea of private variables is that they shouldn't be accessed, and I do want it to work this way when using the module in the rest of the program, but I need it for the purpose of checking the internal workings of the module.

说我有以下简化示例:

module mod
  implicit none
  private
  integer :: value
  public :: set_value

contains

subroutine set_value(input)
  implicit none
  integer,intent(in) :: input
  value=input
end subroutine

end module

现在,我想测试该子例程,看看它是否确实在做我想要的:我想编写一个使用该模块的程序,并使用输入8调用例程 set_value 检查内部变量 value 是否现在为8.

And I now want to test the subroutine to see if it is actually doing what I want: I would like to write a program that uses the module, calls the routine set_value with input 8 and then checks if the internal variable value is now 8.

我可以这样做吗?还是有另一种方法可以对私有变量的初始化程序进行单元测试?

Can I do this? Or is it there another way to unit test initializers of private variables?

推荐答案

您看到三种方法.

  1. 编写一个get函数以获取值并进行测试.您在注释中指出这不是次优的,所以..

  1. write a get function to get the value and test. You indicate in the comments that this is sub-optimal though, so..

如果您具有支持Fortran 2003的编译器(例如,现代Fortran编译器的任何最新版本),请使用 protected 属性(而不是 private 属性.这将使您的变量可以从任何代码中读取,但不能修改.这将强制其只能通过setter函数进行设置,但您可以在单元测试中直接检查其值.

If you have a compiler with Fortran 2003 support (e.g. any recent version of a modern Fortran compiler), declare the variable with the protected attribute instead of the private attribute. This will allow your variable to be read from any code, but not modified. This will enforce that it can only be set via your setter function but you can inspect its value directly in your unit test.

integer, protected :: value

  • 最后,如果其他所有操作均失败,则可以有条件地编译模块,以便有时变量不是私有的.例如,执行以下操作:

  • Lastly, if all else fails, you can conditionally compile the module so that sometimes the variable is not private. For example, do this:

    module mod
      implicit none
      private
      integer :: value
      public :: set_value
    
    #ifdef UNITTESTING
      public :: value
    #endif
    
    contains
    ...
    end module
    

    然后将文件名从 .f90 更改为 .F90 ,以便对其进行预处理(至少在gfortran和ifort上).正常编译时, value 将是私有的,但是如果改用标志 -DUNITTESTING 进行编译,则 value 将是公共的.编译测试用例时,可以使用该标志,它们现在可以直接检查变量.

    Then change the filename from .f90 to .F90 so that it will be pre-processed (at least on gfortran and ifort). When you compile it normally, value will be private, but if you instead compile with the flag -DUNITTESTING then value will be public. When you compile your test cases, you use that flag and they can now inspect the variable directly.

    这篇关于如何在fortran模块中访问私有变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆