Fortran 77 - subroutine in separate file

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
3 replies · 22K views
jf22901
Messages
55
Reaction score
1
Hi all

I am currently using subroutines, and placing them at the end of the main program. However, I was wondering if it is possible to save them to a separate file, which the main program then calls?

For example, in the program below I call the subroutine 'SUB', which is located at the end of the program 'TEST'. Is there any way in which it could be split so that the program 'TEST is in a file called 'test.f' and the subroutine is in a file called 'sub.f'? That way I could call the same subroutines from different programmes, rather than having to put them at the end all the time.

Many thanks,

Jack

Code:
      PROGRAM TEST
      IMPLICIT NONE
      INTEGER X, Y, Z, TOTAL, TOT
      PRINT *, 'Enter numbers X,Y,Z where Y > X'
      READ *, X, Y, Z
      CALL SUB(X, Y, Z, TOTAL)
      PRINT *, 'TOTAL =', TOTAL
      END
C***********************************************************************
C Subroutine called above is located below
C***********************************************************************
      SUBROUTINE SUB(A, B, C, TOT)
      INTEGER TOT, A, B, C, I
      TOT=C
      DO 10 I=A,B
            TOT = TOT*I
10    END DO
      RETURN
      END
 
Last edited:
Physics news on Phys.org
I should add that to compile the above program (assuming I've called it 'test.f'), I would type at the command line:

ifort -C test.f -o test.exe
./test.exe

Jack
 
Try this:

ifort -C test.f sub.f -o test.exe

I have gfortran, not ifort, and I don't use the -C switch. For me, this works:

gfortran test.f sub.f -o test.exe

This recompiles the subroutine every time. If you have a really big subroutine, or a collection of subroutines in a single file, that takes a long time to compile, you can compile them separately and then link them in when you compile the main program. For me it would look like this:

gfortran sub.f -c

which produces an "object file" sub.o. Note that the switch is lowercase 'c' not uppercase 'C'. Then

gfortran test.f sub.o -o test.exe
gfortran foobar.f sub.o -o foobar.exe
etc.

The .o extension signals that the file doesn't need to be compiled, just linked into the compiled program.
 
Last edited:
Brilliant - works a treat. Thanks very much Jon.

However, I'm slightly worried that I tried it and it worked first time. That's not supposed to happen with programming is it?! :-p