本文介绍了如何调用外部函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下功能

REAL FUNCTION myfunction(x)

    IMPLICIT NONE
    REAL, INTENT(IN) :: x
    myfunction = SIN(x)

END FUNCTION myfunction

在名为myfunction.f90

的文件中

我想在其他f90文件中使用此功能.我该怎么办?

解决方案

在现代Fortran中推荐的方法是创建一个模块,我们称它为例如神话".在这种情况下,您可以创建一个包含以下内容的文件mymath.f90:

module mymath
contains
  function myfunction(x) result(r)
    real, intent(in) :: x
    real             :: r

    r = sin(x)
  end function
end module

然后添加另一个文件main.f90,如下所示:

program main
  use :: mymath

  print *,myfunction(3.1416/2)
end program

然后,您只需将源文件编译在一起:

gfortran mymath.f90 main.f90

生成的可执行文件应能按预期工作.

如果您真的更喜欢远离模块,则可以这样制作mymath.f:

function myfunction(x) result(r)
  real, intent(in) :: x
  real             :: r

  r = sin(x)
end function

并使main.f90像这样:

program main
  real, external :: myfunction

  print *,myfunction(3.1416/2)
end program

它可以编译并像其他解决方案一样工作.请注意,如果您选择使用external而不是module,则编译器通常不会检查您提供给myfunction的参数是否具有正确的数字,类型和尺寸-将来可能会使调试复杂化. /p>

I have the following function

REAL FUNCTION myfunction(x)

    IMPLICIT NONE
    REAL, INTENT(IN) :: x
    myfunction = SIN(x)

END FUNCTION myfunction

in a file called myfunction.f90

I want to use this function in other f90 file. How can I do this?

解决方案

The recommended way to do this in modern Fortran would be to create a module, let's call it e.g. "mymath". In that case, you can create one file mymath.f90 containing something like this:

module mymath
contains
  function myfunction(x) result(r)
    real, intent(in) :: x
    real             :: r

    r = sin(x)
  end function
end module

Then another file main.f90 like this:

program main
  use :: mymath

  print *,myfunction(3.1416/2)
end program

Then you just compile the source files together:

gfortran mymath.f90 main.f90

The resulting executable should work as expected.

EDIT:

If you really prefer to stay away from modules, then you can make mymath.f like this:

function myfunction(x) result(r)
  real, intent(in) :: x
  real             :: r

  r = sin(x)
end function

And make main.f90 like this:

program main
  real, external :: myfunction

  print *,myfunction(3.1416/2)
end program

It compiles and works like the other solution. Note that if you choose to use external instead of module, the compiler will usually not check that the arguments you give to myfunction have the right number, types, and dimensions — which may complicate debugging in the future.

这篇关于如何调用外部函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 17:50