Fortran 模块
模块就像一个包,你可以在其中保存你的函数和子程序,以防你正在编写一个非常大的程序,或者你的函数或子程序可以在多个程序中使用。
模块为您提供了一种在多个文件之间拆分程序的方法。
模块用于:
- 打包子程序、数据和接口块。
- 定义可由多个程序使用的全局数据。
- 声明可以在您选择的任何程序中可用的变量。
- 将一个模块完全导入到另一个程序或子程序中以供使用。
模块的语法
模块由两部分组成:
- 语句声明的规范部分
- 包含子程序和函数定义部分
模块的一般形式是:
module name[statement declarations][contains [subroutine and function definitions] ]end module [name]
在程序中使用模块
您可以通过 use 语句将模块合并到程序或子程序中:
use name
请注意:
- 您可以根据需要添加任意多的模块,每个模块都将位于单独的文件中并单独编译。
- 一个模块可以在各种不同的程序中使用。
- 一个模块可以在同一个程序中多次使用。
- 模块规范部分中声明的变量是模块的全局变量。
- 在模块中声明的变量成为使用该模块的任何程序或程序中的全局变量。
use语句可以出现在主程序中,也可以出现在使用特定模块中声明的程序或变量的任何其他子程序或模块中。
实例
module constantsimplicit nonereal, parameter :: pi = 3.1415926536real, parameter :: e = 2.7182818285containssubroutine show_consts()print*, "Pi = ", piprint*, "e = ", eend subroutine show_constsend module constantsprogram module_exampleuse constantsimplicit nonereal :: x, ePowerx, area, radiusx = 2.0radius = 7.0ePowerx = e ** xarea = pi * radius**2call show_consts()print*, "e raised to the power of 2.0 = ", ePowerxprint*, "Area of a circle with radius 7.0 = ", areaend program module_example
结果为:
Pi = 3.14159274e = 2.71828175e raised to the power of 2.0 = 7.38905573Area of a circle with radius 7.0 = 153.938049
模块中变量和子程序的可访问性
默认情况下,模块中的所有变量和子程序都可以通过 use 语句供使用模块代码的程序使用。
但是,您可以使用 private 和 public 属性控制模块代码的可访问性。当您将某些变量或子程序声明为私有时,它在模块外部不可用。
实例
以下实例可以演示:
在前面的例子中,我们有两个模块变量,e 和 pi。让我们将其设为私有并观察输出:
module constantsimplicit nonereal, parameter,private :: pi = 3.1415926536real, parameter, private :: e = 2.7182818285containssubroutine show_consts()print*, "Pi = ", piprint*, "e = ", eend subroutine show_constsend module constantsprogram module_exampleuse constantsimplicit nonereal :: x, ePowerx, area, radiusx = 2.0radius = 7.0ePowerx = e ** xarea = pi * radius**2call show_consts()print*, "e raised to the power of 2.0 = ", ePowerxprint*, "Area of a circle with radius 7.0 = ", areaend program module_example
当您编译并执行上述程序时,它会给出以下错误消息:
ePowerx = e ** x1Error: Symbol 'e' at (1) has no IMPLICIT typemain.f95:19.13:area = pi * radius**21Error: Symbol 'pi' at (1) has no IMPLICIT type
由于 e 和 pi 都被声明为私有,程序 module_example 无法再访问这些变量。
但是,其他模块子程序可以访问它们:
module constantsimplicit nonereal, parameter,private :: pi = 3.1415926536real, parameter, private :: e = 2.7182818285containssubroutine show_consts()print*, "Pi = ", piprint*, "e = ", eend subroutine show_constsfunction ePowerx(x)result(ePx)implicit nonereal::xreal::ePxePx = e ** xend function ePowerxfunction areaCircle(r)result(a)implicit nonereal::rreal::aa = pi * r**2end function areaCircleend module constantsprogram module_exampleuse constantsimplicit nonecall show_consts()Print*, "e raised to the power of 2.0 = ", ePowerx(2.0)print*, "Area of a circle with radius 7.0 = ", areaCircle(7.0)end program module_example
结果如下:
Pi = 3.14159274e = 2.71828175e raised to the power of 2.0 = 7.38905573Area of a circle with radius 7.0 = 153.938049