用fortran链接多个文件

use*_*451 3 fortran file external subroutine

我是Fortran的新手,但我正试图找到一种方法,我可以从我编写的程序中检索信息,而不将它们包含在我的新文件中作为子程序.到目前为止,我的新文件中有4个子程序,我希望能够将半径输入到所有4个并接收各自的输出.

这是我的代码的基本格式 - 基本上我想表明我需要4个独立的程序,以获得当前程序表达式所需的所有变量.到目前为止,我已经尝试使用include和call表达式,但是他们无法检索我需要的信息带回到我的文件中,他们提出了"不适用"的答案.

program practicedynamo

    implicit none

    real:: A,B,C, Radius

    real::Bsquared,Vsquared

    read*,radius

    call programA(radius,A)

    call programB(radius,B)

    call programC(radius,C)


    Vsquared=(1.0/3.0)*B

    Bsquared= 4*pi*density*Vsquared

    gradient=radius*C

    Rvector=Bsquared*Vsquared*gradient

    ThetaVector=Rvector*sin(A)

end program practicedynamo

!and then my four subroutines would be placed afterwards
!here is an example of one of my subroutines within my actual code (the version above has been simplified and I've changed the variables)

subroutine testdensity(radius,density)

implicit none

    real::radius,x,sunradius,density

   if (radius>0.and.radius<=695500000) then

        sunradius=695500000

        x=radius/sunradius

        density=((519*x**4.0)-(1630*x**3.0)+(1844*x*x)-(889*x)+155)

        print*,"                                             "

        density=density*1000

        print*,"the density is",density, "kg per meters cubed"

    else

        print*, "this radius is not an option for the sun"

    end if

end subroutine testdensity
Run Code Online (Sandbox Code Playgroud)

cas*_*sey 6

您还没有提到如何编译代码,但这里有一些将多个源文件包含在单个可执行文件中的一般方法.您不需要包含文件,您可以单独编译它们并将它们链接在一起.建议编写一个Makefile来执行此操作,您可以在其他地方找到大量示例.

要将多个文件编译为一个可执行文件,只需在编译时将它们全部列出

gfortran -o output programA.f90 programB.f90 programC.90 mainprogram.f90
Run Code Online (Sandbox Code Playgroud)

如果您不想将它们全部编译在一起或者在构建时必须重新编译,则可以编译单个对象,例如

gfortran -c -o programA.o programA.f90
gfortran -c -o programB.o programB.f90
gfortran -c -o programC.o programC.f90
Run Code Online (Sandbox Code Playgroud)

然后链接为

gfortran -o output mainprogram.f90 programA.o programB.o programC.o
Run Code Online (Sandbox Code Playgroud)

如果您正在尝试使用库并希望程序AC位于独立库中,则可以先按上述方法编译对象,然后

ar rcs libABC.a programA.o programB.o programC.o
Run Code Online (Sandbox Code Playgroud)

然后将您的主程序编译为

gfortran -o output mainprogram.f90 libABC.a 
Run Code Online (Sandbox Code Playgroud)

如果您不使用模块,那么您将负责确保对外部子例程的调用与外部文件中声明的接口匹配.为了安全并让编译器捕获不匹配参数的问题,您可以在程序中声明显式接口或将外部代码放入模块和use主程序中的那些模块中.