Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Passing variables between subroutines in different files using Fortran

  1. Jul 22, 2009 #1
    Good day,

    I'm modifying a Monte Carlo program (MCCCS Towhee) using Fortran and am having trouble passing an argument (a 2x1 array) from a subroutine withing one file (the existing main loop that 'drives' the code) to another subroutine written in another file (an energy calculation, also part of the existing program package). I've written another subroutine (call it 'AAA') in the main loop that receives the array, assigns it to another variable name (same type, size); then, in the other file, I call AAA to receive the array. The code compiles and runs fine until the call to the subroutine is made, and then it exits with a segmentation fault error (which is strange because I've checked and rechecked the type declarations - they seem fine). I'm a newbie to Fortran, so I'm probably not seeing a very simple solution. Since this program has a sophisticated configure and Makefile setup, and if the solution to my problem means that I must create a new *.F file, what changes (if any) must be be made to the files associated with configure and make?

    Many thanks,
  2. jcsd
  3. Aug 22, 2010 #2
    Hi Sheldon-

    I hope this answers your question since it worked for me. I run my FORTRAN code on Snow Leopard. Now I have multiple subroutines in different files that I call in my main program. The way I made it work was to do:

    gfortran -o mainExec mainprogram.f file1.f file2.f .....

    So mainprogram.f is obviously the main program. file1.f has some number of subroutines while file2.f has some other number of different subroutines etc. Once you then run the executable (mainExec) everything should be fine. Hope that helps.
  4. Aug 23, 2010 #3


    User Avatar
    Science Advisor

    When including multiple files, look up MODULES for Fortran. However, I believe you can only use them in Fortran 90 and up. Either way, they make it easier to allow the programmer to package subroutines in a common file. There are also a few different things such as interfaces which allow for even greater functionality.

    As smigs said, in your Makefile, each file needs to be compiled with the correct dependencies with the -c flag, and then the final executable, linking the objects with the -o flag.
  5. Feb 21, 2011 #4
    check with -ffree-form when compiling.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook