Using subroutine inside module in Fortran 90

Viewed 786

I have a question concerning using a subroutine inside a module in Fortran 90. Here is my code

    Module Multiplication
      Subroutine Two_times(input,output)
        Real :: input,output  
        output = input * 2.0  
      End Subroutine Two_times
    End Module    
    Program test_get_command_argument
      Use Multiplication: Two_times

      Real :: i,j

      i = 0.5
      Write (*,*) i

      Call  Two_times(i,j)
      Write (*,*) j

    End Program

I used ifort to compile the above code. I received the following message.


    files_rev.f90(2): error #6218: This statement is positioned incorrectly and/or has syntax errors.
      Subroutine Two_times(input,output)
    --^
    files_rev.f90(4): error #6274: This statement must not appear in the specification part of a module.
        output = input * 2.0  
    ----^
    files_rev.f90(5): error #6786: This is an invalid statement; an END [MODULE] statement is required.
      End Subroutine Two_times
    --^
    files_rev.f90(5): error #6785: This name does not match the unit name.   [TWO_TIMES]
      End Subroutine Two_times
    -----------------^
    files_rev.f90(6): error #6790: This is an invalid statement; an END [PROGRAM]  statement is required.
    End Module 
    ^
    files_rev.f90(9): error #5082: Syntax error, found IDENTIFIER 'MULTIPLICATION' when expecting one of: ( : % [ . = =>
      Use Multiplication: Two_times
    ------^
    files_rev.f90(8): warning #5427: Program may contain only one main entry routine
    Program test_get_command_argument
    --------^
    compilation aborted for files_rev.f90 (code 1)

Why I got #6218 and #6274 error messages and how to fix them?

1 Answers

You are missing a contains keyword before the subroutine declaration and an only keyword after use. Or you can drop : Two_times to use everything in your module. So a working code would look like below:

Module Multiplication
  Contains
  Subroutine Two_times(input,output)
    Real :: input,output  
    output = input * 2.0  
  End Subroutine Two_times
End Module 

Program test_get_command_argument
  Use Multiplication, Only: Two_times
  Real :: i,j

  i = 0.5
  Write (*,*) i

  Call Two_times(i,j)
  Write (*,*) j

End Program

Take a look at this answer, Can't compile with module and main program in same file, as well, for the missing contains.

Related