GFortran and CodeBlocks issue with Modules and Multiple Files

蹲街弑〆低调 提交于 2019-11-29 12:45:16

Assuming what you have written is how your code is, then it appears that the problem is that the module mesh is inside the main program and not a separate file. You should have three files: Mesh.f90, Derivatives.f90 and Main.f90.

Mesh.f90 is exactly as you have it,

module Mesh
   implicit none
   integer :: IMAX,JMAX,NMAX
   real(8), allocatable :: XD(:),YD(:),FX(:,:),FY(:,:)
   real(8) :: PI,E,DX,DY,H,L,RHO,MU
   parameter (PI = ACOS(-1.D0))
   parameter (E = 2.718)
end module Mesh

Derivatives.f90 should be written as another module, using contains:

module Derivatives
   use mesh
  contains
   real(8) function dfdx(f,i)
      real(8) :: f(i:imax)
      integer :: i

      DfDx=(f(i+1)-f(i-1))/(2d0*dx)

   end function dfdx
end module Derivatives

and the Main.f90 will then use both modules. Note that I had to eliminate the variable DfDx; this is because it conflicts with the function DfDx in module Derivatives

program Cavity
   Use Mesh
   use Derivatives
   implicit none
   Real(8), Allocatable :: func(:)
   Real(8) :: Der
   integer :: i  

   IMAX=10
   DX=1./10

   Allocate(xd(IMAX),func(IMAX))

   Do i=1,IMAX
      xd(i)=i*DX
   End Do

   Do i=1,IMAX
      func(i) = xd(i)**2
   End Do

   Der=Dfdx(func,2)
   Write(*,*) Der

End program Cavity

I do not know how CodeBlocks works, but I would presume it lets you choose the compilation order. If that is the case, you should compile Mesh.f90 first, then Derivatives.f90, then compile Main.f90 before linking them to an executable.

When I compiled & linked them, I got an answer of 0.200000002980232; hopefully that links up to what you have as well.

On codeblock, you may go to Project properties > Build targets Then select the file you want to build first (say mod.f90). In the "Selected file properties" go to "Build" Here,change the priority weight. Lower weight implies the file will be built first.

The problem is that in CodeBlocks "projects are built in the order of appearence, from top to bottom" (CodeBlocks Wiki), in other words, the files are compiled alphabetically. Which means that in my case, Derivatives.f90 was being compiled before than Main.f90 causing the error.

A way to circumvent the problem is to set only the Main.f90 file as build target in CodeBlocks:

  • Menu Project/Properties...
  • In Build Target Files at the tab Build targets check only Main.f90

And use the command Include 'File_Name.f90' inside the Main.f90 code to include the other f90 files for compilation in the right order.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!