语言, Fortran专题

Fortran中include和use的使用

Fortran中常用语句参考这篇:Fortran常用语句

在Python中有import命令,可以实现导入其他文件中的函数以及运行整个导入文件的功能。在Fortran中有include和use命令。其中,include有类似于复制粘贴的效果,前提是inlcude的文件和主文件在同一个文件夹中或者在环境文件夹中。use是实现调用模块的功能。具体例子如下。

主文件 example.f90 :

! This code is supported by the website: https://www.guanjihuan.com
! The newest version of this code is on the web page: https://www.guanjihuan.com/archives/34966


module module_1  ! 第一个模块

  implicit none
  contains  ! 模块中包含以下子程序和函数

  subroutine subroutine_1()  ! 模块中的子程序
    write(*,*) 'test_1'
  end subroutine subroutine_1

  function function_1(x) result(y) ! 模块中的函数
  double precision x, y
    y = 2.d0*x
  end function function_1
  
end module module_1


include 'example_include_1.f90'  ! include文件中包含第二个模块


program main

use module_1
use module_2

implicit none
double precision x, function_3, function_4
x = 1.d0

call subroutine_1()
write(*,*) function_1(x)

call subroutine_2()
write(*,*) function_2(x)

call subroutine_3()
write(*,*) function_3(x)

call subroutine_4()
write(*,*) function_4(x)

end program main


subroutine subroutine_3()
write(*,*) 'test_3'
end subroutine subroutine_3


function function_3(x) result(y)
double precision x, y
y = 8.d0*x
end function function_3

include 'example_include_2.f90'  ! include文件中包含第四个子程序和第四个函数

子文件 example_include_1.f90 :

module module_2

      implicit none
      contains  ! 模块中包含以下子程序和函数
    
      subroutine subroutine_2()  ! 模块中的子程序
         write(*,*) 'test_2'
      end subroutine subroutine_2

      function function_2(x) result(y) ! 模块中的函数
          double precision x, y
            y = 4.d0*x
      end function function_2
      
end module module_2

子文件 example_include_2.f90 :

subroutine subroutine_4()
    write(*,*) 'test_4'
end subroutine subroutine_4


function function_4(x) result(y)
    double precision x, y
    y = 16.d0*x
end function function_4

运行结果:

 test_1
   2.00000000000000
 test_2
   4.00000000000000
 test_3
   8.00000000000000
 test_4
   16.0000000000000

补充说明:

  • module只能在主函数前面,所以要把第一个include语句放在主函数之前。
  • subroutine和function不一定要放在主函数前面。
  • 在调用模块中的函数时,在主函数中好像不需要对函数名function_1, function_2的数据类型进行声明,不会报错。而在调用非模块中的函数时,在主函数中需要对函数名function_3, function_4的数据类型进行声明。
643 次浏览

【说明:本站主要是个人的一些笔记和代码分享,内容可能会不定期修改。为了使全网显示的始终是最新版本,这里的文章未经同意请勿转载。引用请注明出处:https://www.guanjihuan.com

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Captcha Code