gpt4 book ai didi

file - 用fortran链接多个文件

转载 作者:行者123 更新时间:2023-12-01 09:57:02 24 4
gpt4 key购买 nike

我是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com