file - 用fortran链接多个文件

标签 file fortran 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

最佳答案

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

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

gfortran -o output programA.f90 programB.f90 programC.90 mainprogram.f90

如果您不想将它们全部编译在一起或在构建时必须重新编译,您可以编译单个对象,例如
gfortran -c -o programA.o programA.f90
gfortran -c -o programB.o programB.f90
gfortran -c -o programC.o programC.f90

然后链接为
gfortran -o output mainprogram.f90 programA.o programB.o programC.o

如果您尝试使用库并希望程序 A-C 位于独立库中,则可以先按上述方式编译对象,然后
ar rcs libABC.a programA.o programB.o programC.o

然后将您的主程序编译为
gfortran -o output mainprogram.f90 libABC.a 

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

关于file - 用fortran链接多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24149679/

相关文章:

c++ - fopen 没有完全打开文件

function - Fortran - 从子例程返回匿名函数

random - 如何在 CUDA FORTRAN 中生成随机数?

graph - 如何可视化 Fortran(90 或更高版本)源代码,例如使用 Graphviz?

javascript - 从外部文件加载外部 json 对象

c++ - 指向具有外部链接的对象的指针作为非类型模板参数

reactjs - React-js项目部署失败。 “serve”无法识别为内部或外部命令

java - 获取 FileInputStream 使用的文件

c - 从C中的逗号分隔文本文件中读取各种长度的数据

python - 在路径中生成文件,但有时会返回生成器